0% found this document useful (0 votes)
8 views

javascript basics

The document provides an overview of JavaScript data types, including primitive and non-primitive types, and explains key concepts such as undefined vs. null, type coercion, and variable declaration methods. It also covers hoisting, execution context, and the differences between var, let, and const. Additionally, it discusses the behavior of functions and asynchronous code in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

javascript basics

The document provides an overview of JavaScript data types, including primitive and non-primitive types, and explains key concepts such as undefined vs. null, type coercion, and variable declaration methods. It also covers hoisting, execution context, and the differences between var, let, and const. Additionally, it discusses the behavior of functions and asynchronous code in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

1. What are the different data types in JavaScript?

Answer:
JavaScript supports eight data types.
Primitive types (immutable):

 String

 Number

 Boolean

 undefined

 null

 BigInt

 Symbol

Non-primitive type (mutable):

 Object (including Arrays, Functions, Dates, etc.)

🔹 2. What is the difference between undefined and null?

Answer:

 undefined means a variable has been declared but has not been assigned a value.

 null is an assignment value that represents no value or empty value.

Example:

js

CopyEdit

let a;

console.log(a); // undefined

let b = null;

console.log(b); // null

🔹 3. What is the type of NaN?

Answer:
The type of NaN is "number".
This is because NaN is a special value representing an invalid number, like the result of 0 / 0.

js

CopyEdit

typeof NaN; // "number"


🔹 4. How does the typeof operator work in JavaScript?

Answer:
The typeof operator returns a string indicating the type of the operand. It's commonly used for type checking.

Examples:

js

CopyEdit

typeof 42; // "number"

typeof 'hello'; // "string"

typeof true; // "boolean"

typeof undefined; // "undefined"

typeof {}; // "object"

typeof []; // "object"

typeof null; // "object" (legacy bug)

typeof function(){}; // "function"

🔹 5. What is the result of typeof null? Why?

Answer:
typeof null returns "object" due to a bug in the language’s implementation that dates back to the first version of
JavaScript. Although null is a primitive type, typeof mistakenly identifies it as "object".

🔹 6. What is the difference between primitive and non-primitive data types?

Answer:

 Primitive types are immutable and hold single values (e.g., string, number, boolean, etc.).

 Non-primitive types (objects) are mutable and can hold multiple values or collections.

Primitives are compared by value, while objects are compared by reference.

🔹 7. Is JavaScript statically or dynamically typed?

Answer:
JavaScript is a dynamically typed language, meaning variables can hold values of any type without declaring the type
explicitly.

js

CopyEdit

let a = 10; // number


a = "hello"; // now a string

🔹 8. What are the falsy values in JavaScript?

Answer:
Falsy values are values that evaluate to false in a boolean context. They include:

 false

 0

 -0

 "" (empty string)

 null

 undefined

 NaN

All other values are truthy.

🔹 9. How do you check if a variable is an array?

Answer:
Use Array.isArray() which returns true if the variable is an array:

js

CopyEdit

Array.isArray([1, 2, 3]); // true

Array.isArray({}); // false

🔹 10. How does JavaScript handle type coercion?

Answer:
JavaScript performs implicit type conversion (coercion) in certain operations:

js

CopyEdit

'5' + 2 // "52" (number is coerced to string)

'5' - 2 // 3 (string is coerced to number)

true + 1 // 2 (true is coerced to 1)

Use === to avoid unintended coercion.

🔹 11. What is the difference between == and ===?

Answer:
 == (loose equality): compares values after type coercion.

 === (strict equality): compares both value and type.

js

CopyEdit

'5' == 5; // true

'5' === 5; // false

🔹 12. What is the difference between typeof and instanceof?

Answer:

 typeof checks the type of a value (works best with primitives).

 instanceof checks if an object is an instance of a constructor.

js

CopyEdit

typeof []; // "object"

[] instanceof Array; // true

🔹 13. Can the type of a variable change at runtime?

Answer:
Yes. JavaScript allows variables to change their type dynamically.

js

CopyEdit

let data = 10;

data = 'text'; // valid

🔹 14. What is a Symbol in JavaScript?

Answer:
Symbol is a primitive data type introduced in ES6 to create unique identifiers for object properties.

js

CopyEdit

let id = Symbol('id');

let user = {

[id]: 123

};
Each symbol is guaranteed to be unique.

🔹 15. What’s the difference between Object, Array, and Function types?

Answer:

 Object: basic key-value pairs

 Array: ordered list of values, index-based

 Function: callable object with code execution

js

CopyEdit

typeof {}; // "object"

typeof []; // "object"

typeof function() {}; // "function"

Would you like me to prep some advanced-level or practical scenario questions on data types next?

4o

You said:

whag is the maeing of immutable and mutable

ChatGPT said:

Great question!

🔹 What is immutable?

Immutable means "cannot be changed" after it's created.

 When a value is immutable, you cannot modify it directly.

 Instead, if you want to "change" it, you create a new value.

✅ Example (immutable):

js

CopyEdit

let str = "hello";

str[0] = "H";

console.log(str); // "hello" (unchanged)

 Strings in JavaScript are immutable. Even if you try to change a character, the original string stays the same.

🔹 What is mutable?

Mutable means "can be changed or modified" after creation.


 Objects and arrays in JavaScript are mutable, meaning you can change their content without creating a new one.

✅ Example (mutable):

js

CopyEdit

let arr = [1, 2, 3];

arr[0] = 99;

console.log(arr); // [99, 2, 3]

 Arrays are mutable—you changed the first element directly.

1. What is a variable in JavaScript?

Answer:
A variable in JavaScript is a named container used to store data that can be changed later. It allows us to reference and
manipulate values in a program.

js

CopyEdit

let name = "Alice";

let age = 25;

Variables can hold any data type — strings, numbers, booleans, objects, etc.

2. What are the different ways to declare variables in JavaScript?

Answer:
JavaScript provides three keywords to declare variables:

1. var – function-scoped (older, avoid using)

2. let – block-scoped, can be updated

3. const – block-scoped, cannot be reassigned

js

CopyEdit

var x = 10;

let y = 20;

const z = 30;

3. What is the difference between let, const, and var?


Feature var let const

Scope Function Block Block

Reassignment Allowed Allowed ❌ Not allowed

Hoisting Yes (undefined) Yes (but not initialized) Yes (but not initialized)

Use Today ❌ Avoid ✅ Preferred ✅ Use for constants

Example:

js

CopyEdit

function test() {

if (true) {

var a = 1; // accessible outside the if-block

let b = 2; // block-scoped

const c = 3; // block-scoped

console.log(a); // 1

console.log(b); // Error

4. What is hoisting in JavaScript?

Answer:
Hoisting is JavaScript's default behavior of moving declarations to the top of the scope before code execution.

 var is hoisted and initialized with undefined

 let and const are hoisted but not initialized — accessing them before declaration causes a ReferenceError

js

CopyEdit

console.log(a); // undefined

var a = 5;

console.log(b); // ReferenceError

let b = 10;

5. Can a const variable be changed?


Answer:
You cannot reassign a const variable, but if it holds an object or array, the contents can be changed.

js

CopyEdit

const user = { name: "John" };

user.name = "Mike"; // ✅ allowed

user = {}; // ❌ Error: Assignment to constant variable

6. What is the Temporal Dead Zone (TDZ)?

Answer:
The Temporal Dead Zone is the time between the hoisting of a let or const variable and its actual initialization. Accessing
the variable in this zone causes a ReferenceError.

js

CopyEdit

console.log(x); // ReferenceError

let x = 10;

7. Are JavaScript variables dynamically typed?

Answer:
Yes. JavaScript is a dynamically typed language, meaning you don't declare a variable's type. A variable can hold any
type, and the type can change at runtime.

js

CopyEdit

let data = 5; // number

data = "hello"; // now a string

8. Can you declare a variable without var, let, or const?

Answer:
Yes, but it’s not recommended. Declaring a variable without any keyword creates an implicit global variable, which can
lead to bugs.

js

CopyEdit

function example() {

x = 10; // Implicit global


}

example();

console.log(x); // 10

9. What is variable shadowing?

Answer:
Variable shadowing occurs when a variable declared inside a block (or function) has the same name as a variable in an
outer scope. The inner variable “shadows” the outer one in that scope.

js

CopyEdit

let x = 1;

function test() {

let x = 2; // shadows outer x

console.log(x); // 2

test();

console.log(x); // 1

10. What happens if you try to redeclare a variable?

 With var: allowed (not good)

 With let and const: ❌ not allowed in the same scope

js

CopyEdit

var a = 10;

var a = 20; // ✅ allowed

let b = 10;

let b = 20; // ❌ SyntaxError

1. What is the order of execution in a JavaScript program?


Answer:
JavaScript follows a top-to-bottom execution pattern and is single-threaded. It executes code line by line in the global
execution context unless interrupted by:

 Function calls (new execution context)

 Asynchronous code (moved to the task queue or microtask queue)

2. What is an execution context in JavaScript?

Answer:
An execution context is the environment in which JavaScript code runs. There are three types:

 Global Execution Context (GEC)

 Function Execution Context (FEC)

 Eval Execution Context (rare)

Each execution context has:

 Variable Environment

 Scope Chain

 this binding

3. Explain what happens during the creation and execution phase of an execution context.

Answer:

 Creation Phase:

o Memory is allocated for variables and functions.

o Variables declared with var are hoisted and set to undefined.

o Functions are hoisted with their definitions.

o let and const are hoisted but kept in the Temporal Dead Zone.

 Execution Phase:

o Code is executed line-by-line.

o Variables get assigned actual values.

o Function calls push new contexts to the call stack.

4. What is hoisting and how does it affect execution?

Answer:
Hoisting moves variable and function declarations to the top of their scope during the creation phase. This means they
can be used before their actual line of code — but only in certain ways:

js
CopyEdit

console.log(a); // undefined

var a = 5;

console.log(b); // ReferenceError

let b = 10;

5. What will be the output of this code? Explain line by line.

js

CopyEdit

function test() {

console.log(x); // ?

var x = 10;

console.log(x); // ?

test();

Answer:

 First console.log(x) → undefined (because x is hoisted)

 After x = 10, second console.log(x) → 10

6. What is the call stack and how does it work line-by-line?

Answer:
The call stack is a data structure that keeps track of function calls.

 When a function is called, it’s pushed onto the stack.

 When the function returns, it’s popped off the stack.

 JavaScript always runs the top item on the stack.

Example:

js

CopyEdit

function a() {

console.log("Inside a");

b();

}
function b() {

console.log("Inside b");

a();

Execution Order (line-by-line):

1. Global → enters

2. a() pushed

3. "Inside a" logged

4. b() pushed

5. "Inside b" logged

6. b() popped

7. a() popped

7. What happens if you call a function before it is defined?

js

CopyEdit

greet(); // ?

function greet() {

console.log("Hello");

Answer:
It works fine because function declarations are hoisted with their entire definition.

8. What happens in this case with arrow functions?

js

CopyEdit

sayHi(); // ?

var sayHi = () => console.log("Hi");

Answer:
This will throw a TypeError because sayHi is hoisted as undefined (just like var), but it's not initialized until the
assignment line.
9. What will be the output?

js

CopyEdit

var a = 1;

function outer() {

var a = 2;

function inner() {

console.log(a);

inner();

outer();

Answer:
Output: 2
Because the inner() function has access to its outer lexical environment and picks a from outer()'s scope.

10. Does JavaScript execute async code line-by-line?

Answer:
No. JavaScript handles async code using the event loop, which defers execution using the task queue (for setTimeout,
etc.) or the microtask queue (for promises).

Example:

js

CopyEdit

console.log("A");

setTimeout(() => console.log("B"), 0);

console.log("C");

Output:

css

CopyEdit

You might also like