JavaScript Mastery Part 1

Basics of JavaScript

JavaScript Mastery Part 1

Hey! JavaScript

Syllabus: Click to view the Syllabus - link

Frontend Roadmap: One Stop Frontend Document - link

console: a console is an object in JavaScript and the log() is a function.

console.log, alert, prompt, and confirm are all part of the browser. They are JavaScript functions that allow you to interact with the user.

  • console.log is used to print messages to the browser's console. This is useful for debugging your code.

  • alert is used to display a message to the user. This is useful for getting the user's attention.

  • prompt is used to ask the user for input. This is useful for getting the user's name or age.

  • confirm is used to ask the user to confirm something. This is useful for making sure the user wants to delete a file or submit a form.

All of these functions are modal, which means that they block the user from interacting with the rest of the page until they are dismissed. This can be useful, but it can also be annoying if you use it too often.

The console.log(), console.error(), and console.warn() are three methods in JavaScript that are used to print messages to the browser's console.

The console.log() method is used to print general messages to the console. It is the most commonly used of the three methods.

The console.error() method is used to print error messages to the console. It is typically used when something goes wrong in your code.

The console.warn() method is used to print warning messages to the console. It is typically used to warn the developer about something that might be a problem but is not necessarily an error.

Here are some examples of how to use these methods:

console.log("This is a log message.");
console.error("This is an error message.");
console.warn("This is a warning message.");

ES5 vs ES6: The var keyword is in ES5 and the let keyword is introduced in ES6.

ES5 Functions:

  1. Function Statement

  2. Function Expression

  3. Anonymous Function

ES6 Functions:

FAT Arrow Function

  1. Basic FAT Arrow Function

  2. FAT Arrow Function with one parameter

  3. FAT Arrow Function with implicit return

use strict: "Use strict" is a directive that tells the JavaScript engine to run the code in strict mode. Strict mode is a set of rules that make JavaScript code more secure and easier to write.

  1. Preventing errors

  2. Improving performance

  3. Making code more readable

syntax: 'use strict';

let vs var: Var can be declared and accessed globally. Let can be declared globally, but its access is limited to the block in which it is declared. Variables declared using var can be re-declared and updated within the same scope. Variables declared with let can be updated but not re-declared within the same scope.

we can declare a let variable with one name only once. in Var, we can do it several times.

const: The const keyword in JavaScript is used to declare a constant variable. A constant variable is a variable whose value cannot be changed once it has been initialized.

Null: is a deliberate assignment of a valueless state. It is often used to indicate that a variable does not have a value yet, or that it has been intentionally set to empty.

undefined: is the default value of a variable that has not been assigned a value. It is also used to indicate that a property does not exist on an object.

for the const variable, you should always give value to the variable.

Data Types:

String Methods:

== VS ===: The == operator performs a loose equality comparison that performs type coercion if necessary to make the comparison possible. The === operator, on the other hand, performs a strict equality comparison that does not perform type coercion and requires the operands to have the same type (as well as the same value).

Primitive Type: In the primitive type, the value is copied, and the value is not changeable.

Reference Type: In the reference type, the value is a reference, and the value can be changed.

Array Methods:

Dot VS Brackets Notation:

Dot Notation only allows static keys while Bracket Notation accepts dynamic keys. Static key here means that the key is typed directly, while Dynamic key here means that the key is evaluated from an expression.

function expression: the function expression is a function declaration wrapped in a variable.

Arrow function: Arrow function is a function expression wrapped in a variable.

hoisting: hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Hoisting is only allowed for function declarations. it is only allowed with the variable which is declared with var(ES5), not in case of variable declared in let and const(ES6).

Callback Function: Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function. Callback functions are important in JavaScript because they let you create asynchronous code that doesn't block the main thread of execution. This enables you to perform other tasks, such as user interface (UI) updates or other API calls, while an asynchronous action is executing.

GitHub code: link

functions vs methods:

"when we create a function inside the object is called method in JavaScript"

The main difference between a function and a method in JavaScript is that a method is a function that belongs to an object, while a function is a standalone entity.

Method:

A method can access and modify the properties of the object it belongs to, while a function cannot. This is because a method has a reference to the object it belongs to, while a function does not.

To create a method, you define a function inside of an object. For example:

var obj = {
  name: "Vitthal Korvan",
  age: 24,
  greet: function() {
    console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
  }
};

To call a method, you use the dot notation. For example:

obj.greet();

This will print the following to the console:

Hello, my name is Vitthal Korvan and I am 24 years old.

Function:

You can also create functions that are not associated with any object. These functions are called standalone functions. Standalone functions can be called anywhere in your code, and they do not have access to any object's properties.

For example:

function add(a, b) {
  return a + b;
}

To call a standalone function, you simply use the function's name. For example:

var sum = add(1, 2);

This will assign the value 3 to the variable sum.

In general, it is a good practice to use methods whenever possible, as this makes your code more readable and maintainable. However, there are some cases where you may need to use a standalone function.

this keyword:

value of the this keyword in different scenario:

call() and apply() method:

There are two methods in JavaScript that can be used to call a function with a different this object: the call() method and the apply() method. Both methods take the function to be called as the first argument, and any number of arguments to be passed to the function as subsequent arguments. The difference between the two methods is that the call() method takes the arguments as individual parameters, while the apply() method takes the arguments as an array.

The syntax for the call() method is as follows:

function.call(thisObject, arg1, arg2, ...)

where:

  • function is the function to be called

  • thisObject is the object that the this keyword will refer to inside the function

  • arg1, arg2, ... are the arguments to be passed to the function

The syntax for the apply() method is as follows:

function.apply(thisObject, [arg1, arg2, ...])

where:

  • function is the function to be called

  • thisObject is the object that the this keyword will refer to inside the function

  • [arg1, arg2, ...] is an array of the arguments to be passed to the function

Here is an example of how to use the call() method:

function greet(name) {

  console.log(`Hello, ${name}!`);

}

const person = {
  name: "Vitthal"
};
// Call the greet() function with the person object as the this object.
greet.call(person);

Output:

Hello, Vitthal!

Here is an example of how to use the apply() method:

function greet(names) {
  console.log(`Hello, ${names.join(", ")}!`);
}
const people = ["Vitthal", "Mahadev", "Anand", "Lingesh"];
// Call the greet() function with the people array as the arguments.
greet.apply(null, people);

Output:

Hello, Vitthal, Mahadev, Anand, Lingesh!

bind() Method:

The bind() method in JavaScript is a function method that creates a new function that, when called, has its this keyword set to a provided value. The bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.

The syntax for the bind() method is:

function.bind(thisArg, ...args)

where:

  • function is the function to be bound.

  • thisArg is the value to be set as the this keyword for the new function.

  • args are the arguments to be passed to the new function.

The bind() method can be used in a variety of situations, such as:

  • When you need to call a function from a different context.

  • When you need to pass arguments to a function that are not available in the current context.

  • When you need to create a new function that has the same behavior as an existing function, but with a different context or arguments.

Here is an example of how to use the bind() method:

function greet(name) {
  console.log(`Hello, ${name}!`);
}

const person = {
  name: 'Vitthal Korvan',
};

const greetPerson = greet.bind(person);

greetPerson(); // logs "Hello, Vitthal Korvan!"

Prototypal Inheritance:

In prototypal inheritance, every object has a prototype object. The prototype object is a hidden object that contains properties and methods that are available to the object. When an object tries to access a property or method that it does not have, it will look for the property or method on its prototype object. If the property or method is not found on the prototype object, then the object will try to access it on its parent object. This process continues until the property or method is found, or until the end of the prototype chain is reached.

Closures:

A closure is a function that has access to the variables in the scope in which it was created, even after that scope has closed. This is because a closure is a lexical scoping function. Lexical scoping means that the scope of a variable is determined by where it is declared in the code, not where it is used.

Here is an example of a closure in JavaScript:

function outer() {
  var name = "Vitthal Korvan";
  function inner() {
    console.log(name); // "Vitthal Korvan"
  }
  return inner;
}

var innerFunc = outer();
innerFunc(); // "Vitthal Korvan"

Event Delegation:

In JavaScript is a pattern that efficiently handles events. Events can be added to a parent element instead of adding to every single element. It refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated.

Higher Order Functions:

A “higher-order function” is a function that accepts functions as parameters and/or returns a function.

Try and Catch:

the try block is executed first. If it throws an error, the code in the catch block will be executed. The code in the finally block will always be executed, regardless of whether an error occurs or not.

Custom Events:

JavaScript Interview Questions:

Null vs Undefined:

Undefined means a variable has been declared but has yet not been assigned a value.Null is an assignment value. It can be assigned to a variable as a representation of no value.

Null -> Object type

Undefined -> Undefined type

ways to create objects in JavaScript:

  1. using curly braces

  2. using new keyword

  3. Object.create({})

  4. user constructor function

  5. using class

In JavaScript, objects are one of the fundamental data types, and there are several ways to create objects. Here are some common methods:

  1. Object Literal: The simplest way to create an object is by using an object literal, which is a comma-separated list of name-value pairs enclosed in curly braces {}.

     var person = {
       firstName: 'Vitthal',
       lastName: 'Korvan',
       age: 24,
       getInfo: function() {
         return this.firstName + ' ' + this.lastName + ', ' + this.age + ' years old';
       }
     };
    
  2. Constructor Function: You can use a constructor function to create multiple instances of objects. Constructor functions are invoked using the new keyword.

     function Person(firstName, lastName, age) {
       this.firstName = firstName;
       this.lastName = lastName;
       this.age = age;
       this.getInfo = function() {
         return this.firstName + ' ' + this.lastName + ', ' + this.age + ' years old';
       };
     }
    
     var person = new Person('Vitthal', 'Korvan', 24);
    
  3. Object.create method: The Object.create() method creates a new object with the specified prototype object.

     var personPrototype = {
       getInfo: function() {
         return this.firstName + ' ' + this.lastName + ', ' + this.age + ' years old';
       }
     };
    
     var person = Object.create(personPrototype);
     person.firstName = 'Vitthal';
     person.lastName = 'Korvan';
     person.age = 24;
    
  4. ES6 Class: With the introduction of ES6, you can use the class syntax to create objects with a constructor and methods.

     javascriptCopy codeclass Person {
       constructor(firstName, lastName, age) {
         this.firstName = firstName;
         this.lastName = lastName;
         this.age = age;
       }
    
       getInfo() {
         return `${this.firstName} ${this.lastName}, ${this.age} years old`;
       }
     }
    
     var person = new Person('Vitthal', 'Korvan', 24);