Article Image

Javascript

Interview

Javascript Concepts Part 1

New Features in ES6

ECMAScript 6 (ES6) introduced several powerful features to JavaScript, enhancing its functionality and readability. Key features include:

  • The let keyword
  • The const keyword
  • Arrow Functions
  • Promises
  • Map Object

Example: Map Object

// Create a new Map
const fruits = new Map();

// Add new elements to the Map
fruits.set("apples", 500);
fruits.set("bananas", 300);
fruits.set("oranges", 200);
  • Set Object
// Create a Set
const letters = new Set();

// Add values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
  • Classes
class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
}

Difference Between let, var, and const

Variable Declarations Comparison

The var keyword has a known issue where variables can be accidentally overwritten. For instance:

var camper = "James";
var camper = "David";
console.log(camper); // Output: David

With let, however, a variable can only be declared once, and attempting to declare it again results in an error:

let camper = "James";
let camper = "David";  // Uncaught SyntaxError: Identifier 'camper' has already been declared

Scope Comparison of var and let

Variables declared with var have a global scope, even if they are inside a block:

var numArray = [];
for (var i = 0; i < 3; i++) {
  numArray.push(i);
}
console.log(numArray);  // Output: [0, 1, 2]
console.log(i);         // Output: 3 (global scope)

In contrast, variables declared with let are scoped to the block, statement, or expression:

let printNumTwo;
for (let i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo()); // Output: 2
console.log(i);  // Error: i is not defined

const Behavior

Unlike var and let, the const keyword requires variables to be initialized upon declaration and prevents reassignment. However, objects assigned to const variables remain mutable:

const s = [5, 6, 7];
s[2] = 45;
console.log(s); // Output: [5, 6, 45]

s = [1, 2, 3];  // Error: Assignment to constant variable

Variable Shadowing

Variable shadowing occurs when a variable in a local scope shares the same name as one in an outer scope, thus overriding the outer variable within the local context:

let number = 10;

function displayDouble() {
  let number = 3;
  number *= 2;
  console.log(number); // Output: 6
}

displayDouble();
console.log(number);  // Output: 10

Strings in JavaScript

Strings in JavaScript are immutable, meaning their values cannot be changed once they are assigned. For example:

let myStr = "Bob";
myStr[0] = "J";  // Does not alter the value of myStr
console.log(myStr); // Output: "Bob"

Escape Sequences in Strings

JavaScript provides escape sequences for inserting special characters in strings:

Code     Output
\'       single quote
\"       double quote
\\       backslash
\n       newline
\r       carriage return
\t       tab
\b       word boundary
\f       form feed

== vs === in JavaScript

The == (equality) operator compares values for equality, performing type coercion when the types are different. In contrast, === (strict equality) does not perform type coercion, making it more precise.

Examples:

3 === 3         // true
3 === '3'       // false
1 == [1]        // true
1 === [1]       // false
null == undefined // true
const number = 1234;
const stringNumber = '1234';

console.log(number == stringNumber);  // true
console.log(number === stringNumber); // false

Here, despite both values looking similar, the type differs (number vs string), leading to a true result for == but false for ===.

Understanding this in JavaScript

In JavaScript, the this keyword refers to the context from which it is called. It is used to access properties of an object within its methods.

Example:

const person = {
  name: 'John',
  age: 30,
  greet: function() {
    console.log('The name is ' + this.name);
  }
};

person.greet(); // Output: The name is John

Contextual Use of this

  • Global Scope: In the global context, this refers to the global object (e.g., window in browsers).
let a = this;
console.log(a);  // Output: Window {}
  • Functions: In regular functions, this refers to the global object.
function greet() {
  console.log(this);  // Output: Window {}
}
greet();
  • Constructor Functions: When used in a constructor function, this refers to the newly created object.
function Person() {
  this.name = 'Jack';
  console.log(this);
}

let person1 = new Person(); // Output: Person { name: 'Jack' }
  • ES6 Classes: In ES6 classes, this refers to the instance of the class.
class Person {
  constructor(name) {
    this.name = name;
  }
}

const person1 = new Person('John');
const person2 = new Person('Jack');

console.log(person1.name);  // Output: John
console.log(person2.name);  // Output: Jack
  • Object Methods: Inside an object method, this refers to the object itself.
const person = {
  name: 'Jack',
  age: 25,
  greet() {
    console.log(this);        // Output: { name: 'Jack', age: 25, greet: [Function: greet] }
    console.log(this.name);   // Output: Jack
  }
};

person.greet();
  • Arrow Functions: Arrow functions do not have their own this. Instead, they inherit this from their parent scope.
const greet = {
  name: 'Jack',
  sayHi() {
    let hi = () => console.log(this.name); // Inherits `this` from sayHi method
    hi();  // Output: Jack
  }
};

greet.sayHi();
  • Strict Mode: In strict mode, this is undefined when used in a function context.
'use strict';
function greet() {
  console.log(this);  // Output: undefined
}
greet();

Difference Between Arrow Functions and Regular Functions

The primary difference between arrow functions and regular functions lies in how the this keyword is handled.

  • In regular functions, this refers to the context where the function is invoked.
  • Arrow functions do not have their own this. Instead, they inherit this from their enclosing scope.

Example:

function Person() {
  this.name = 'Jack';
  this.sayName = function() {
    console.log(this.name);
  };
}

let x = new Person();
x.sayName();  // Output: Jack

Thanks for reading!!!

Muneer Ahmed

Author

0