Java Script New 2 Flashcards
What are the different data types present in javascript?
Primitive data types can store only a single value: numbers, string, boolean, bigint, null undefined symbol
typeof “John Doe” // Returns “string”
typeof 3.14 // Returns “number”
typeof true // Returns “boolean”
typeof 234567890123456789012345678901234567890n // Returns bigint
typeof undefined // Returns “undefined”
typeof null // Returns “object” (kind of a bug in JavaScript)
typeof Symbol(‘symbol’) // Returns Symbol
Referent type - to store multiple and complex values, :
Object, array,
// Collection of data in key-value pairs
var obj1 = {
x: 43,
y: “Hello world!”,
z: function(){
return this.x;
}
}
// Collection of data as an ordered list
var array1 = [5, “Hello”, true, 4.1];
Explain Hoisting in javascript.
Hoisting is the default behaviour of javascript where all the variable and function declarations are moved on top
Variable initializations are not hoisted, only variable declarations are hoisted
var x;
console.log(x); // Outputs “undefined” since the initialization of “x” is not hoisted
x = 23;
To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code
“use strict”
x= 23 //Gives an error since ‘x’ is not declared
var x;
Why do we use the word “debugger” in javascript?
The debugger for the browser must be activated in order to debug the code. Built-in debuggers may be switched on and off, requiring the user to report faults. The remaining section of the code should stop execution before moving on to the next line while debugging.
Difference between “ == “ and “ === “ operators
Both are comparison operators. The difference between both the operators is that “==” is used to compare values whereas, “ === “ is used to compare both values and types
let x = 2;
let y = “2”;
(x == y) // Returns true since the value of both x and y is the same
(x === y) // Returns false since the typeof x is “number” and typeof y is “string
Difference between var and let keyword in javascript
The keyword ‘Var’ has a function scope. Anywhere in the function, the variable specified using var is accessible
‘let’ is the scope of a variable declared with the ‘let’ keyword limited to the block in which it is declared.
Block Scope.
In ECMAScript 2015, let and const are hoisted but not initialized.
Referencing the variable in the block before the variable declaration results in a ReferenceError because the variable is in a “temporal dead zone” from the start of the block until the declaration is processed
Explain Implicit Type Coercion in javascript.
Implicit type coercion - automatic conversion of value from one data type to another. It takes place when the operands of an expression are of different data types.
String coercion - using the ‘ + ‘ operator. When a number is added to a string, the number type is always converted to the string type.
var x = 3;
var y = “3”;
x + y // Returns “33”
Boolean Coercion - takes place when using logical operators, ternary operators, if statements, and loop checks. To understand boolean coercion in if statements and operators, we need to understand truthy and falsy values.
Truthy values are those which will be converted (coerced) to true. Falsy values are those which will be converted to false.
All values except false, 0, 0n, -0, “”, null, undefined, and NaN are truthy values.
var x = 0;
var y = 23;
if(x) { console.log(x) } // The code inside this block will not run since the value of x is 0(Falsy)
if(y) { console.log(y) } // The code inside this block will run since the value of y is 23 (Truthy)
Logical operators always return one of the operands.
OR ( | | ) operator - If the first value is truthy, then the first value is returned. Otherwise, always the second value gets returned.
AND ( && ) operator - If both the values are truthy, always the second value is returned. If the first value is falsy then the first value is returned or if the second value is falsy then the second value is returned.
var x = 220;
var y = “Hello”;
var z = undefined;
x | | y // Returns 220 since the first value is truthy
x | | z // Returns 220 since the first value is truthy
x && y // Returns “Hello” since both the values are truthy
y && z // Returns undefined since the second value is falsy
if( x && y ){
console.log(“Code runs” ); // This block runs because x && y returns “Hello” (Truthy)
}
if( x || z ){
console.log(“Code runs”); // This block runs because x || y returns 220(Truthy)
Equality coercion takes place when using ‘ == ‘ operator. As we have stated before
The ‘ == ‘ operator compares values and not types.
While the above statement is a simple way to explain == operator, it’s not completely true
The reality is that while using the ‘==’ operator, coercion takes place.
The ‘==’ operator, converts both the operands to the same type and then compares them.
Example:
var a = 12;
var b = “12”;
a == b // Returns true because both ‘a’ and ‘b’ are converted to the same type and then compared. Hence the operands are equal.
Coercion does not take place when using the ‘===’ operator. Both operands are not converted to the same type in the case of ‘===’ operator.
Is javascript a statically typed or a dynamically typed language
JavaScript is a dynamically typed language. In a dynamically typed language, the type of a variable is checked during run-time in contrast to a statically typed language, where the type of a variable is checked during compile-time.
Since javascript is a loosely(dynamically) typed language, variables in JS are not associated with any type. A variable can hold the value of any data type.
A variable that is assigned a number type can be converted to a string type:
var a = 23;
var a = “Hello World!”;
What is NaN property in JavaScript
NaN property represents the “Not-a-Number” value. It indicates a value that is not a legal number.
typeof of NaN will return a Number.
To check if a value is NaN, we use the isNaN() function,
Note- isNaN() function converts the given value to a Number type, and then equates to NaN.
isNaN(“Hello”) // Returns true
isNaN(345) // Returns false
isNaN(‘1’) // Returns false, since ‘1’ is converted to Number type which results in 0 ( a number)
isNaN(true) // Returns false, since true converted to Number type results in 1 ( a number)
isNaN(false) // Returns false
isNaN(undefined) // Returns true
Explain passed by value and passed by reference.
Primitive data types are passed by value and non-primitive data types are passed by reference.
var x = 2;
In the above example, we created a variable x and assigned it a value of “2”. In the background, the “=” (assign operator) allocates some space in the memory, stores the value “2” and returns the location of the allocated memory space. Therefore, the variable x in the above code points to the location of the memory space instead of pointing to the value 2 directly.
Assign operator dealing with primitive types:
var y = 234;
var z = y;
In the above example, the assign operator knows that the value assigned to y is a primitive type (number type in this case), so when the second line code executes, where the value of y is assigned to z, the assign operator takes the value of y (234) and allocates a new space in the memory and returns the address. Therefore, variable z is not pointing to the location of variable y, instead, it is pointing to a new location in the memory.
var y = #8454; // y pointing to address of the value 234
var z = y;
var z = #5411; // z pointing to a completely new address of the value 234
// Changing the value of y y = 23;
console.log(z); // Returns 234, since z points to a new address in the memory so changes in y will not effect z
From the above example, we can see that primitive data types when passed to another variable, are passed by value. Instead of just assigning the same address to another variable, the value is passed and new space of memory is created.
Assign operator dealing with non-primitive types:
var obj = { name: “Vivek”, surname: “Bisht” };
var obj2 = obj;
In the above example, the assign operator directly passes the location of the variable obj to the variable obj2. In other words, the reference of the variable obj is passed to the variable obj2.
var obj = #8711; // obj pointing to address of { name: “Vivek”, surname: “Bisht” }
var obj2 = obj;
var obj2 = #8711; // obj2 pointing to the same address
// changing the value of obj1 obj1.name = “Akki”;
console.log(obj2);
// Returns {name:”Akki”, surname:”Bisht”} since both the variables are pointing to the same address.
From the above example, we can see that while passing non-primitive data types, the assign operator directly passes the address (reference).
Therefore, non-primitive data types are always passed by reference.
What is an Immediately Invoked Function in JavaScript?
IIFY is a function that runs as soon as it is defined.
(function(){
// Do something;
})();
While executing javascript code, whenever the compiler sees the word “function”, it assumes that we are declaring a function in the code. Therefore, if we do not use the first set of parentheses, the compiler throws an error because it thinks we are declaring a function, and by the syntax of declaring a function, a function should always have a name.
function() {
//Do something;
}
// Compiler gives an error since the syntax of declaring a function is wrong in the code above.
To remove this error, we add the first set of parenthesis that tells the compiler that the function is not a function declaration, instead, it’s a function expression.
The second set of parenthesis:
(function (){
//Do something;
})();
From the definition of an IIFE, we know that our code should run as soon as it is defined. A function runs only when it is invoked. If we do not invoke the function, the function declaration is returned:
(function (){
// Do something;
})
// Returns the function declaration
Therefore to invoke the function, we use the second set of parenthesis.
What do you mean by strict mode in javascript and characteristics of javascript strict-mode?
In ECMAScript 5, a new feature called JavaScript Strict Mode allows you to write a code or a function in a “strict” operational environment. In most cases, this language is ‘not particularly severe’ when it comes to throwing errors. In ‘Strict mode,’ however, all forms of errors, including silent errors, will be thrown. As a result, debugging becomes a lot simpler. Thus programmer’s chances of making an error are lowered.
Characteristics of strict mode in javascript
Duplicate arguments are not allowed by developers.
In strict mode, you won’t be able to use the JavaScript keyword as a parameter or function name.
The ‘use strict’ keyword is used to define strict mode at the start of the script. Strict mode is supported by all browsers.
Explain Higher Order Functions in javascript.
Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. Higher-order functions are a result of functions being first-class citizens in javascript.
function higherOrder(fn) {
fn();
}
higherOrder(function() { console.log(“Hello world”) });
function higherOrder2() {
return function() {
return “Do something”;
}
}
var x = higherOrder2();
x() // Returns “Do something”
Explain “this” keyword.
The “this” keyword refers to the object that the function is a property of. The value of the “this” keyword will always depend on the object that is invoking the function.\
function doSomething() {
console.log(this);
}
doSomething();
The output of the above code will be the global object. Since we ran the above code inside the browser, the global object is the window object.
var obj = {
name: “vivek”,
getName: function(){
console.log(this.name);
}
}
obj.getName();
The getName function is a property of the object obj , therefore, this keyword will refer to the object obj, and hence the output will be “vivek”.
var obj = {
name: “vivek”,
getName: function(){
console.log(this.name);
}
}
var getName = obj.getName;
var obj2 = {name:”akshay”, getName };
obj2.getName();
The output will be “akshay”. Although the getName function is declared inside the object obj, at the time of invocation, getName() is a property of obj2, therefore the “this” keyword will refer to obj2.
Whenever the function is invoked, check the object before the dot. The value of this . keyword will always be the object before the dot.If there is no object before the dot-like in example1, the value of this keyword will be the global object.
var obj1 = {
address : “Mumbai,India”,
getAddress: function(){
console.log(this.address);
}
}
var getAddress = obj1.getAddress;
var obj2 = {name:”akshay”};
obj2.getAddress();
This keyword refers to the object obj2, obj2 does not have the property “address”‘, hence the getAddress function throws an error.
What do you mean by Self Invoking Functions?
Without being requested, a self-invoking expression is automatically invoked (initiated). If a function expression is followed by (), it will execute automatically. A function declaration cannot be invoked by itself.
Normally, we declare a function and call it, anonymous functions may be used to run a function automatically when it is described and will not be called again. And there is no name for these kinds of functions.
Explain call() methods
It’s a predefined method in javascript.
This method invokes a method (function) by specifying the owner object.
function sayHello(){
return “Hello “ + this.name;
}
var obj = {name: “Sandy”};
sayHello.call(obj); // Returns “Hello Sandy”
call() method allows an object to use the method (function) of another object.
var person = {
age: 23,
getAge: function(){
return this.age;
}
}
var person2 = {age: 54};
person.getAge.call(person2); // Returns 54
call() accepts arguments:
function saySomething(message){
return this.name + “ is “ + message;
}
var person4 = {name: “John”};
saySomething.call(person4, “awesome”); // Returns “John is awesome”