Header Ads Widget

Responsive Advertisement

Javascript logic question and answer

  JS Logic: Common Questions and Answers

Understanding JavaScript logic is essential for every developer. This blog delves into common JavaScript logic questions and provides comprehensive answers to help you enhance your problem-solving skills.

javascript logic question and answer

JavaScript Variable Declarations:

JavaScript offers various ways to declare variables, including var, let, and const. Here's a breakdown of their usage:

var: Allows variable redeclaration and reassignment.
let: Permits only variable reassignment, not redeclaration.
const: Prevents both redeclaration and reassignment.


// var, let, connst variable
// in var variable
var x = 'hello';
var x = 'techie' //we can redeclare the variable
x = 'change-value' // reassign  the variable as well.


// in let variable
let y = 'hello ';
// let y='techie'   //cannot redeclare the same variable
y = 'words-change value' //reassign the variable can be done.


// in const variable
const z = 'hello';
// const z ='techie';//cannot redeclare the variable
// z='sss' // cannot reassign the variable


if (true) {
    var x1 = 'hello techies'
}
console.log(x1)  //can access the variable 'x1'


if (true) {
    let y1 = 'change '   //same as const variable case, cannot access
}
// console.log(y1) //cannot access


for (var i = 1; i <= 5; i++) {

}
console.log(i)//  can access the variable
for (let i = 1; i <= 5; i++) {

}
console.log(i)
// ReferenceError: i is not defined ===> EXPLANATION: in let and const case, we give us error

//TEMPLATE STRING  or TEMPLATE LITERALS means using backtick and dollar sign with curly braces for defining the dynamic value in the string

// REST OPERATOR: below example of how we tackle multiple arguments

function sol(name, course, ...arguments) {
    let sum = 0;
    for (let i of arguments) {
        sum += i
    }
    console.log(`hello ${name}, ${course} : ${sum}`)
}
sol('function, 'bap', 22, 33, 435, 354);



Q:) 

let greetings;
greetigns = {}; // Typo!
console.log(greetigns);

the answer is: ReferenceError: greetigns is not defined

Q:)

function Animal(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

const member = new Animal('lion', 'tiger');
Animal.getFullName = function() {
  return `${this.firstName} ${this.lastName}`;
};

console.log(member.getFullName());

The output: TypeError

EXPLANATION:

function Animal(firstName, lastName):

 This line defines a constructor function named Animal, which takes two parameters: firstName and lastName. Constructor functions in JavaScript are used to create objects with a certain structure.

this.firstName = firstName; 

and this.lastName = lastName;

 Inside the Animal functionthis refers to the object being created by the constructor function. These lines assign the firstName and lastName arguments passed to the constructor function to the properties of the object being created.


const member = new Animal('lion', 'tiger');
This line creates a new object called a member using the Animal constructor function. The firstName is set to 'lion' and the lastName is set to 'tiger'.


Animal.getFullName = function() { ... };:

 This line adds a getFullName method directly to the Animal function object itself, not to the individual instances created with the Animal constructor. This means that every instance of Animal won't inherit this method automatically.


return ${this.firstName} ${this.lastName};

 Inside the getFullName method, this refers to the Animal function itself. However, when the getFullName method is called on member, this will not refer to the member object because getFullName is not bound to individual instances.


console.log(member.getFullName());
This line tries to call the getFullName method on the member object. However, since getFullName is not a method of individual instances created by the Animal constructor, it will result in an error.


The output of console.log(member.getFullName())

will be an error message similar to: "TypeError: member.getFullName is not a function".

FOR FIXING THIS ISSUE: 
To fix this issue and make getFullName a method that can be called on individual instances, you should define it inside the constructor function itself using this. Here's how you can do it

function PersonOf(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
 
  this.getFullName = function() {
    return `${this.firstName} ${this.lastName}`;
  };
}

const member = new Person('tonu', 'hardik');
console.log(member.getFullName()); // Output: tonu hardik

EXPLANATION :

function PersonOf(firstName, lastName): This line defines a constructor function named Person, which takes two parameters: firstName and lastName. Constructor functions in JavaScript are used to create objects with a certain structure.


this.firstName = firstName; and this.lastName = lastName;
Inside the PersonOf functionthis refers to the object being created by the constructor function. These lines assign the firstName and lastName arguments passed to the constructor function to the properties of the object being created.


const member =  new Person('tonu', 'hardik');
 This line creates a new object called member using the Person constructor function. The firstName property of member is set to 'tonu' and the lastName property is set to 'hardik'.


Q:)

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

sum(1, '2');

EXPLANATION:

 JavaScript is a dynamically typed language: in this, we don't specify what types of variables are. Values can automatically be converted into another type without we knowing, which is called implicit type coercion. Coercion is converting from one type into another.


In the above example, JavaScript converts the number 1 into a string, in order for the function to make sense and return a value. During the addition of a numeric type (1) and a string type ('2'), the number is treated as a string. We can concatenate strings like "Hello" + "World", so what's happening here is "1" + "2" which returns "12". 


Q:)

let number = 0;
console.log(number++);
console.log(++number);
console.log(number);

EXPLANATION:
console.log(number++);
Here, number++ is a postfix unary operator, which means it takes the current value of the number, uses that value for the operation, and then increments the value of number by 1.

 So, when console.log(number++) runs, it first prints the current value of number (which is 0), and then it increments the value of number to 1.


console.log(++number);
 In contrast, ++number is a prefix unary operator. It first increments the value of number by 1, and then it returns the updated value. So, when console.log(++number) runs, it increments the value of the number from 1 to 2 and then prints that updated value (which is 2).


console.log(number):
 Finally, console.log(number) prints the current value of the number, which is 2 since it was incremented in the previous step.

So, the output will be:

0 (from console.log(number++))

2 (from console.log(++number))

2 (from console.log(number))

In simple terms, number++ increments a number after it uses its current value, while ++number increments the number before using its value


Q:)

function getInfo(strOne, strTwo, strThree) {
  console.log(StrOne);
  console.log(strTwo);
  console.log(strThree);
}

const personData = 'tony';
const age = 21;

getInfo`${personData} is ${age} years old`;

Theory:

This code shows us a feature called "tagged template literals" in JavaScript.

Here's what's happening step by step:

getInfo${personData} is ${age} years old;
This line uses a tagged template literal. It's a special kind of string literal that allows you to call a function with the template literal's string parts as arguments, along with the interpolated values.

Inside the template literal, ${personData} and ${age} are placeholders for variables. They will be replaced by the values of the variables personData and age respectively.


The getInfo function is called with three arguments:

The first argument is an array containing the string parts of the template literal (in this case, an array with one element: ' is ' years old').

The second and third arguments are the values of the variables person and age respectively.

Inside the getInfo function, the three arguments are logged to the console using console.log.


So, the output of the code will be:

['', ' is ', ' years old']

tony

21

EXPLANATION:

The first console.log(one); logs the first element of the array, which is an empty string ''.

The second console.log(two); logs the second element of the array, which is the value of the variable person ('tony').

The third console.log(three); logs the third element of the array, which is the value of the variable age (21).


Q:)
function checkAge(data) {
  if (data === { urAge: 19 }) {
    console.log('You are age is 19');
  } else if (data == { urAge: 18 }) {
    console.log('You are 18.');
  } else {
    console.log(`You are child`);
  }
}
checkAge({ urAge: 18 });
answer is:  You are child


EXPLANATION:
in js, we have to data-types, primitives are compared by their value, while objects are compared by their reference. 
JavaScript checks if the objects have a reference to the same location in memory.

The two objects that we are comparing don't have the same location in memory:
The object we passed as a parameter refers to a different location in memory than the object we used in order to check equality.

This is why both { age: 18 } === { age: 18 } and { age: 18 } == { age: 18 } return false.

Q:)

function getAge(...args) {
  console.log(typeof args);
}

getAge(21);
answer is object

EXPLANATION:

here are we use rest parameters (...args)

 which is use to collect all remaining arguments into an array. An array is an object, so typeof args returns "object"


Q:)
function getAge() {
  'use strict';
  age = 21;
  console.log(age);
}

getAge();
    asnwer is Reference-Error

EXPLANATION:

When we add "use strict" at the beginning of our JavaScript code, it enforces a stricter set of rules for code execution. One of the benefits of using "use strict" is that it helps prevent unintended behaviors, such as accidentally declaring global variables.


For instance, let's consider a scenario where we have not explicitly declared a variable called age, but we intend to use it within our code. If we forget to declare age and simply use it within a function, without "use strict", JavaScript would automatically create a global variable named age. This can lead to unexpected behavior and hard-to-debug issues, especially in larger codebases.


However, with "use strict", JavaScript treats such scenarios as errors, specifically a reference error. This means that if we try to use age without declaring it first, JavaScript will throw an error, alerting us to the mistake. By enforcing stricter rules, "use strict" helps catch errors early in development, promoting cleaner and more reliable code.


So, by using "use strict", we ensure that our code follows best practices and avoids common pitfalls, ultimately leading to more maintainable and robust applications.


Q:)
const sum = eval('10*10+5');
answer is 105

EXPLANATION:

`eval` is a JavaScript function that takes a string of code and runs it as if it were written directly in the program. In this case, the string contains a mathematical expression: "10 * 10 + 5". When `eval` runs this code, it calculates the result of the expression, which is 105. So, `eval` essentially computes the value of the expression given as a string.


Q:)
var num = 8;
var num = 10;

console.log(num);

EXPLANATION:

Using the var keyword in JavaScript allows you to declare multiple variables with the same name within the same scope. However, if you do this, the variable will only retain the latest assigned value.


On the other hand, with let and const, we cannot declare multiple variables with the same name within the same block or scope. Attempting to do so will result in a syntax error. This is because let and const are block-scoped, meaning they are limited to the block in which they are defined and cannot be redeclared within that block.


Q:)
for (let i = 1; i < 5; i++) {
  if (i === 3) continue;
  console.log(i);
}
the answer is 1 3 4

EXPLANATION:

The continue statement skips an iteration if a certain condition returns true


Q:)
const a = {};
const b = { key: 'b' };
const c = { key: 'c' };

a[b] = 123;
a[c] = 456;

console.log(a[b]);

EXPLANATION:

In JavaScript, when we use objects as keys in another object, they are automatically converted into strings. If we try to set an object as a key in an object and stringify it, it becomes "[object Object]". So, when we assign a value to a["[object Object]"], we are essentially setting the key as "[object Object]".

Later, if we try to set another object as a key in a, it will also be implicitly converted to a string. So, when we set c as a key in a, it also becomes "[object Object]". Therefore, when we log a[b], it's actually referring to a["[object Object]"]. Since we previously assigned a["[object Object]"] as 456,
 it returns 456


Q:)

const foo = () => console.log('First');
const bar = () => setTimeout(() => console.log('Second'));
const baz = () => console.log('Third');

bar();
foo();
baz();

EXPLANATION:

This code defines three functions: foo, bar, and baz. Each function print a message to the console: 'First', 'Second', and 'Third' respectively.

The bar function is a bit special because it uses setTimeout to delay the execution of its inner function, which logs 'Second', by a short amount of time. This delay allows the other functions to execute before 'Second' is logged.

Here's what happens:

bar() is called first. It schedules the inner function (which logs 'Second') to run after a short delay but continues to the next line without waiting for it to finish.

foo() is called next. It logs 'First' immediately.

baz() is called last. It logs 'Third' immediately.

So, the output will be:

First
Third
Second


Q:)
const person = { name: 'Ram ji' };

function sayHi(age) {
  return `${this.name} is ${age}`;
}

console.log(sayHi.call(person, 21));
console.log(sayHi.bind(person, 21));

EXPLANATION:

Both .call() and .bind() are methods in JavaScript that allow us to control the value of this keyword within a function.

.call() is used to call a function immediately and explicitly specify the object to which this refers to inside that function. When you use .call(), the function is executed right away.

.bind() is different. It returns a new function with this value bound to the specified object, but it doesn't execute the function immediately. Instead, it creates a copy of the function with the specified this value, allowing you to call it later.

So, .call() immediately calls the function with a specific this value, while.bind() creates a new function with a specific this value but doesn't execute it right away.


Q:)
function sayHi() {
  return (() => 0)();
}

console.log(typeof sayHi());

EXPLANATION:
The function sayHi returns the result of an Immediately Invoked Function Expression (IIFE). This IIFE returns the value 0, which is a number type.

In JavaScript, the typeof operator helps determine the type of a value. It can return various types such as undefined, boolean, number, string, symbol, function, and object. However, it's important to note that typeof null returns "object".

So, in simpler terms, the sayHi function gives back the result of a quick function call that returned a number, and we can check the type of this result using typeof, which tells us it's a number.


Q:)

console.log(typeof typeof 1);


EXPLANATION:

typeof 1 returns "number". typeof "number" returns "string"


Q:)
const numbers = [1, 2, 3];
numbers[10] = 11;
console.log(numbers);
SOLUTION: [1, 2, 3, empty x 7, 11]


EXPLANATION:

When we assign a value to an element in an array that is beyond the length of the array, JavaScript creates what are known as "empty slots".

These slots don't contain any actual value but appear as if they are filled with some placeholder like "empty" or "undefined".
For example, if we have an array [1, 2, 3] and we assign a value to index 10, JavaScript will create "empty slots" between index 3 and 10.

Depending on where we run our code (different browsers, Node.js, etc.), these empty slots may be represented differently, but they essentially indicate that those positions in the array are undefined or don't contain any meaningful value.

Post a Comment

0 Comments