0% found this document useful (0 votes)
26 views8 pages

Self Assessment Js DataTypes and Variables

Self Assessment Js DataTypes and Variables
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)
26 views8 pages

Self Assessment Js DataTypes and Variables

Self Assessment Js DataTypes and Variables
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/ 8

1. What are the different types of primitive data types in JavaScript?

In JavaScript, there are several primitive data types. These are the most basic data types that
are not objects and have no methods. Here are the different types of primitive data types in
JavaScript:

1. Number:
o Represents both integer and floating-point numbers.
o Examples: 42, 3.14, -7.
2. BigInt:
o Represents integers with arbitrary precision.
o Used for numbers beyond the safe integer limit for the Number type.
o Example: 1234567890123456789012345678901234567890n.
3. String:
o Represents a sequence of characters.
o Strings are immutable.
o Examples: "hello", 'world', `template literal`.
4. Boolean:
o Represents a logical entity with two values: true or false.
o Examples: true, false.
5. Undefined:
o Represents a variable that has been declared but not assigned a value.
o Example: let a; // a is undefined.
6. Null:
o Represents the intentional absence of any object value.
o Example: let b = null;.
7. Symbol:
o Represents a unique and immutable identifier.
o Often used to add unique property keys to an object that won't collide with
keys from any other code.
o Example: let sym = Symbol('description');.

These primitive data types are the fundamental building blocks in JavaScript and are used to
create more complex data structures and objects.

typeof operator: It can be used to determine the type of a given variable or expression. For
example:

console.log(typeof 123); // "number"


console.log(typeof 'Hello'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (this is a known quirk in JavaScript)
console.log(typeof Symbol()); // "symbol"
console.log(typeof 123n); // "bigint"
2. Explain the difference between let and const.

In JavaScript, let and const are both used to declare variables, but they have some key
differences:

let

1. Block Scope: Variables declared with let are block-scoped, meaning they are only
accessible within the block (e.g., { ... }) they are defined in.
2. Reassignment: Variables declared with let can be reassigned to a new value.
3. No Hoisting: Although let variables are hoisted to the top of their block, they are not
initialized. Accessing them before the declaration results in a ReferenceError.

let x = 10;
x = 20; // Allowed

{
let y = 30;
console.log(y); // 30
}
console.log(y); // ReferenceError: y is not defined

const

1. Block Scope: Like let, variables declared with const are block-scoped.
2. No Reassignment: Variables declared with const cannot be reassigned to a different
value after their initial assignment. However, if the variable is an object or array, the
properties or elements can still be modified.
3. No Hoisting: Similar to let, const variables are hoisted to the top of their block but
are not initialized. Accessing them before the declaration results in a
ReferenceError.

Example:

const a = 10;
a = 20; // TypeError: Assignment to constant variable.

const b = { name: 'Alice' };


b.name = 'Bob'; // Allowed, object properties can be modified

{
const c = 30;
console.log(c); // 30
}
console.log(c); // ReferenceError: c is not defined
Summary

 Use let when you need to reassign a variable within its block scope.
 Use const when you want to ensure a variable is not reassigned, but be aware that
objects and arrays declared with const can still have their contents modified.

3. How does type coercion work in JavaScript?


Type coercion in JavaScript refers to the automatic or implicit conversion of values from one data
type to another (such as strings to numbers, objects to booleans, etc.) by the JavaScript engine. This
often happens when operations involve values of different types, or when specific functions expect
certain types of arguments. Type coercion can be explicit or implicit.

Explicit Coercion

Explicit coercion occurs when you manually convert from one type to another using
JavaScript functions or operators.

Examples:

1. String to Number:

let str = "123";


let num = Number(str); // 123

2. Number to String:

let num = 123;


let str = String(num); // "123"

3. Boolean to String:

let bool = true;


let str = String(bool); // "true"

Implicit Coercion

Implicit coercion happens automatically when JavaScript expects a certain type but receives
another.

Examples:

1. Addition of String and Number:

let result = "5" + 2; // "52"


// The number 2 is coerced to a string, and concatenation happens.

2. Subtraction with Strings and Numbers:

let result = "5" - 2; // 3


// The string "5" is coerced to a number, and subtraction happens.

3. Boolean Coercion:

let result = !!"non-empty string"; // true


// A non-empty string is coerced to true.

Coercion Rules

1. . To Boolean:

 Falsy Values: false, 0, -0, 0n (BigInt zero), "" (empty string), null, undefined, and NaN.
 Truthy Values: Everything else.

Boolean(""); // false
Boolean("hello"); // true
Boolean(0); // false
Boolean(42); // true

2. To Number:

 Strings are converted to numbers if possible, otherwise NaN.


 null converts to 0, undefined converts to NaN.

Number("123"); // 123
Number("abc"); // NaN
Number(""); // 0
Number(null); // 0
Number(undefined); // NaN

3. To String:

 All values are converted to their string representation

String(123); // "123"
String(true); // "true"
String(null); // "null"
String(undefined); // "undefined"
Common Implicit Coercion Scenarios

1. Equality Operator (==): The == operator can coerce types to compare values.

"5" == 5; // true
0 == false; // true
null == undefined; // true

2. Arithmetic Operations: Non-numeric values are coerced to numbers

"6" * "2"; // 12
"6" / "2"; // 3
"6" - 2; // 4

3. Logical Operators: Logical operators (&&, ||, !) convert their operands to booleans.

!!"non-empty string"; // true


!!0; // false
"hello" || "world"; // "hello"
"" && "world"; // ""

Avoiding Unexpected Coercion

To avoid unexpected results due to type coercion, it's generally good practice to use the strict
equality operator (===) and explicit type conversion functions.

Example:
let num = "5";
if (num === 5) {
// This will not run, as num is a string and 5 is a number.
}

if (Number(num) === 5) {
// This will run, as num is explicitly converted to a number.
}

Understanding and managing type coercion in JavaScript helps in writing more predictable
and bug-free code.

4o

*Quiz:*

1. Which of the following is not a primitive data type in JavaScript?


- a) String
- b) Number
- c) Object
- d) Boolean

In JavaScript, the primitive data types are:

1. String
2. Number
3. Boolean
4. Undefined
5. Null
6. Symbol (added in ES6)
7. BigInt (added in ES11)

Objects, on the other hand, are not primitive data types. They are complex data structures that
can contain collections of data and more complex entities.

2. What is the output of typeof null?


- a) "object"
- b) "null"
- c) "undefined"
- d) "boolean"

In JavaScript, the typeof operator returns "object" for null. This is actually considered a bug in the
language, but it has been kept this way for backward compatibility reasons. So, even though null is
a primitive value, typeof null will return "object".

3. Which keyword is used to declare a variable that cannot be reassigned?


- a) var
- b) let
- c) const
- d) static

In JavaScript, the const keyword is used to declare a variable that cannot be reassigned. Variables
declared with const are block-scoped and must be initialized at the time of declaration.

4. What does the typeof operator return for an array?


- a) "array"
- b) "object"
- c) "undefined"
- d) "null"
In JavaScript, arrays are a type of object. Therefore, the typeof operator returns "object"
when used on an array. To specifically check if a value is an array, you can use
Array.isArray().

5. What is the result of 2 + "2"?


- a) 22
- b) "22"
- c) 4
- d) "4"

In JavaScript, when you use the + operator with a number and a string, the number is coerced into a
string and the two strings are concatenated. Therefore, 2 + "2" results in the string "22".

6. What will be the output of let a = 10; a = 20;?


- a) Error
- b) 10
- c) 20
- d) undefined

In JavaScript, the let keyword allows you to declare a variable that can be reassigned. Therefore,
the code let a = 10; a = 20; will successfully reassign the value of a to 20.

7. What is the scope of a variable declared with var?


- a) Block scope
- b) Function scope
- c) Global scope
- d) Local scope

In JavaScript, a variable declared with var is function-scoped, meaning it is accessible throughout


the function in which it is declared, regardless of block boundaries (e.g., within if statements or
loops). If declared outside any function, var variables have global scope.

8. How do you check if a variable is undefined?


- a) variable == undefined
- b) typeof variable === "undefined"
- c) variable === undefined
- d) All of the above

You can check if a variable is undefined using any of the following methods:
1. variable == undefined: This works because undefined is a special value that has
a loose equality with undefined. However, this approach may give unexpected
results if the variable has been explicitly set to null or another value.
2. typeof variable === "undefined": This is the safest way to check for undefined
because it doesn’t throw an error if the variable hasn’t been declared. It works even if
the variable is undeclared.
3. variable === undefined: This is a strict comparison that works if the variable is
explicitly declared and not assigned a value. However, it may throw an error if the
variable hasn't been declared.

All three methods are valid, but typeof variable === "undefined" is generally
recommended for its safety and reliability.

9. What will be the output of console.log(1 / 0)?


- a) Infinity
- b) NaN
- c) 0
- d) Error

In JavaScript, dividing a positive number by zero results in Infinity. If you divide a negative
number by zero, you get -Infinity. If you divide zero by zero, you get NaN (Not-a-Number).

10. What does the following code output?


javascript
const x = 5;
x = 10;
console.log(x);

- a) 5
- b) 10
- c) Error
- d) undefined

The const keyword is used to declare variables that are meant to be constant, meaning they
cannot be reassigned after their initial assignment. Trying to reassign x from 5 to 10 will
cause a TypeError and prevent the console.log(x) line from executing.

You might also like