TYPES, VALUES, and VARIABLES Flashcards

1
Q

1) What type of programming language is javaScript?:-

A

javascript is a high-level, dynamic, interpreted programming language that is well-suited for object-oriented and functional programming styles.
-> javascript variables are untyped.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

2) How do you run a js file with node?:-

A

$ node filename.js (in terminal)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

3) What is a programming language’s(e.g javaScript) lexical structure?:-

A

it is the set of elemenary rules that specify how you write programs in that language. (aka) the lowest-level of synax of a language.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

4) What are the types of comments in js:-

A

single-line(//) multi-line(/**/) (Comments may not be nested)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

5) There are three exceptions to the general rule that javaScript interprets line breaks as semicolons when it cannot parse the second line as a continuation of the statement in the first line?:-

A

-> The first exception invloves the return, throw, yeild, break and continue statement.(These statements often stand alone, but sometime are followed by an identifier or expression.)
-> The second exception involves the ++ and −− operators.
-> The third excep‐ tion involves functions defined using concise “arrow” syntax: the => arrow itself must appear on the same line as the parameter list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

6) JavaScript type are divided into two categories: namely?:-

A

primitive types and objects types.
* Primitives are immutable: there is no way to change (or “mutate”) a primitive value.
* Primitives are also compared by value: two values are the same only if they have the same value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

7) JavaScript primitive types include (name 3)?:-

A

numbers, strings(Strings of text) and boolean truth values
* Primitives are immutable: there is no way to change (or “mutate”) a primitive value.
* Primitives are also compared by value: two values are the same only if they have the same value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

8) JavaScript has two additional primitive types that are not numbers, strings or booleans. Name them?:-

A

the special values null and undefined. (each value is considered to be the sole member of its own special type)
* Primitives are immutable: there is no way to change (or “mutate”) a primitive value.
* Primitives are also compared by value: two values are the same only if they have the same value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

9) In ES6 Symbol was added as a?:-

A

new special-purpose type, that enables the definition of language extensions
without harming backword compatibility.
* Symbols were introduce to serve as no-string property names.
* To understand Symbols, you need to know that JavaScript’s fundamental Object type is an unodered collection of
properties, where each property has a name and a value. Property names are typically
(and until ES6, were exclusively) strings. But in ES6 and later, Symbols can also serve this purpose:

let strname = “string name”; // A string to use as a property name
let symname = Symbol(“propname”); // A Symbol to use as a property name
typeof strname // => “string”: strname is a string
typeof symname // => “symbol”: symname is a symbol
let o = {}; // Create a new object
o[strname] = 1; // Define a property with a string name
o[symname] = 2; // Define a property with a Symbol name
o[strname] // => 1: access the string-named property
o[symname] // => 2: access the symbol-named property

  • The Symbol type does not have a literal syntax. To obtain a Symbol value, you call the Symbol() function.
  • This function never returns the same value twice, even when called with the same argument.
    This means that if you call Symbol() to obtain a Symbol value, you can safely use that value as a property
    name to add a new property to an object and do not need to worry that you might be overwriting an
    existing prop‐erty with the same name. Similarly, if you use symbolic property names and
    do not share those symbols, you can be confident that other modules of code in your program will
    not accidentally overwrite your properties.
  • The Symbol() function takes an optional string argument and returns a unique Sym‐ bol value.
    If you supply a string argument, that string will be included in the output of the Symbol’s toString() method.
    Note, however, that calling Symbol() twice with the same string produces two completely different Symbol values.

let s = Symbol(“sym_x”);
s.toString() // => “Symbol(sym_x)”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

10) What is an object?:-

A

any javaScript value that is not a number, string, boolean, null, undefined
or Symbol (that is a member of the type object).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

11) What is an ordinary javaScript objetc?:-

A

is an unordered collection of named values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

12) JavaScript defines a special kind of object called?:-

A

an array (an ordered collection of numbered values)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

13) In addition to basic/ordinary objects and arrays javaScript defines other useful types of object. Name
those 5 objects?:-

A

-> A Set object respesents a set of values.
-> A Map object represents a mapping from values to keys.
-> Various “typed array” types facilitate operations on arrays of bytes and other binary data.
-> The RegExp type represents textual patterns and enables sophisticated matching, searching, and replacing
operations on strings.
-> The Date type represents dates and times and supports rudimentary date arthimetics.
-> Error and its subtypes represents errors that can arise will running javaScript code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

14) In javaScript which two values can method not be invoked on?:-

A

null and undefined.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

15) JavaScript objects are mutable and its primitive types are immutable. what does that mean?:-

A

-> Mutable types can change.
-> Immutable types cannot change. (Strings can be thought of as arrays of characters but they are immuntable)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

16) JavaScript constants and variables are untyped. What does that mean?:-

A

declaractions do not specify what kind of values will be assigned.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

17) The javaScript number format allows you to exactly represent all integers btw?:-

A

−9,007,199,254,740,992 (−25^3) and 9,007,199,254,740,992 (25^3), inclusive.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

18) What is a numeric literal in js?:-

A

numbers that appear directly in the js code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

19) What is the structure of a base 16 literal?:-

A

hexdecimal values start with a 0x or 0X, followed by a string of hexdecimal digints. hexdecimal values go from 0 - 9 and a/A - f/F (10 - 15)

examples
0xff // => 255: (15*16 + 15 * 16)
0xBADCAFE // => 195939070

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

20) ES6 introduces binary and octal interger representations as:-

A

-> base 2 (0b or 0B) 0b10101 // => 21: (116 + 08 + 14 + 02 + 11)
-> base 8 (0o or 0O) 0o377 // => 255: (3
64 + 78 + 71)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

21) Arthimetics in javaScript does not raise errors in case of overflow, underflow and division by zero.
What definitions of js hand this three cases?:-

A

-> When the result of a numeric operation is larger than the largest repre‐ sentable number (overflow),
the result is a special infinity value, Infinity. Similarly, when the absolute value of a negative value becomes
larger than the absolute value of the largest representable negative number, the result is negative infinity, -Infinity.
* The infinite values behave as you would expect: adding, subtracting, multiplying,
or dividing them by anything results in an infinite value (possibly with the sign reversed).
-> Underflow occurs when the result of a numeric operation is closer to zero than the smallest representable number.
In this case, JavaScript returns 0. If underflow occurs from a negative number, JavaScript returns a special value known as “negative zero.”
-> Division by zero is not an error in JavaScript: it simply returns infinity or negative infinity. There is one exception,
however: zero divided by zero does not have a well- defined value, and the result of this operation is the special not-a-number value, NaN.
* JavaScript predefines global constants Infinity and NaN to hold the positive infinity and not-a-number value,
and these values are also available as properties of the Number object:

Infinity // A positive number too big to represent
Number.POSITIVE_INFINITY // Same value
1/0 // => Infinity or NaN
Number.MAX_VALUE * 2 // => Infinity; overflow
NOTE: adding a negtive sign in the example above gives negative infinity.

Number.MIN_VALUE/2 // => 0: underflow
-Number.MIN_VALUE/2 // => -0: negative zero
-1/Infinity // -> -0: also negative 0
-0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

22) What does NaN stand for?:-

A

not-a-number

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

23) When does NaN(not-a-number) arise?:-

A

-> division by zero(can also return -Infinity(negative infinity)).
-> dividing Infinity by Infinity.
-> taking the square root of a negative number.
-> using arthimetic operations on non-numeric operands that cannot be coverted to numbers.

NaN // The not-a-number value
Number.NaN // The same value, written another way
0/0 // => NaN
Infinity/Infinity // => NaN

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

24) What is the unsual feature of the NaN value?:-

A

It does not compare equal to any other value, including itself.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

25) You can write x === NaN to determine if the value of x is NaN. Instead what are the two options for checking if x is equal to NaN?:-

A

x != NaN or Number.isNaN (These expressions wil be true if and only if, x has the
same value as the global constant NaN)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

26) The global function isNaN() is similar to Number.isNaN(). What does it return?:-

A

it returns true if its argument is NaN, or it that argument is non-numeric value that cannot be converted to
a number.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

27) What does Number.isFinite() return?:-

A

it return true if its argument is a number other than NaN, Infinity,
or -Infinity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

28) The global isFinite() function returns?:-

A

true if its argument is a finite number or can be converted to a finite number.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

29) What is the unusual behavior of negative zero in relation to positive zero?:-

A

it compares equal
(even when using strick equal test “===”) to postive zero, The two values are almost indistinguishable,
except when used as a divisor:

let zero = 0; // Regular zero
let negz = -0; // Negative zero
zero === negz // => true: zero and negative zero are equal
1/zero === 1/negz // => false: Infinity and -Infinity are not equal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

30) What is the explation fo
let x = .3 - .2; // thirty cents minus 20 cents
let y = .2 - .1; // twenty cents minus 10 cents
x === y // => false: the two values are not the same!
x === .1 // => false: .3-.2 is not equal to .1
y === .1 // => true: .2-.1 is equal to .1

?:-

A

Binary Floating-Point and Rounding Errors

  • Binary floating-point representations cannot exactly represent numbers as simple as 0.1.
  • If these floating-point approximations are problematic for your programs,
    consider using scaled integers. For example, you might manipulate monetary values as integer
    cents rather than fractional dollars.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

31) As of ES2020 BigInt(Numeric type whose values are integers) was introduce for what purpose?:-

A

was add to js maily to allow the representation of 64-bit intergers, which are required by many other
programming languages and APIs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

32) Why are BigInt not good for cryptography?:-

A

because they do not attempt to prevent timing attacks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

33) What is the synax of a BigInt literal?:-

A

BigInt literals are written as strings of digits followed by
a lowers case ‘n’. By default they are in base 10, but you can use 0X, 0O, or 0B prefixes.

1234n
0b111111n
0o7777n
0x8000000000000000n // => 2n**63n: A 64-bit integer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

34) What is BigInt() function used for?:-

A

for converting regular javaScript nnumbers and strings to
BigInt values.

BigInt(Number.MAX_SAFE_INTEGER) // => 9007199254740991n
let string = “1” + “0”.repeat(100); // 1 followed by 100 zeros.
BigInt(string) // => 10n**100n: one googol

  • Arithmetic with BigInt values works like arithmetic with regular JavaScript numbers,
    except that division drops any remainder and rounds down (toward zero)

1000n + 2000n // => 3000n
3000n - 2000n // => 1000n
2000n * 3000n // => 6000000n
3000n / 997n // => 3n: the quotient is 3
3000n % 997n // => 9n: and the remainder is 9
(2n ** 131071n) - 1n // A Mersenne prime with 39457 decimal digits

  • Although the standard +, -, *, /, %, and ** operators work with BigInt,
    it is important to understand that you may not mix operands of type BigInt with regular number operands.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

35) What does the Date class do?:-

A

it represents and manipulates the numbers that represent date and time.
Date are objects but also have a numerical representation as timestamps, that represent the number of millisseconds
that have elapsed since January 1, 1970.

let timestamp = Date.now(); // The current time as a timestamp (a number).
let now = new Date(); // The current time as a Date object.
let ms = now.getTime(); // Convert to a millisecond timestamp.
let iso = now.toISOString(); // Convert to a string in standard format.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

36) What is a string?:-

A

its the javaScript type for representing text.
* Strings are immuntable ordered sequence of 16-bit values(each character is 16-bit -check if correct-).
* The length of a string isthe number of 16-bit values it contains
* JavaScript does not have a special type for repsenting a single element of a string (character).
To represent a single 16-bit value, simple use a string of length 1.
* As of ES6 strings are iterable(iteration happens on the actual characters of the string, not the 16-bit values.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

37) What are the escape for
The NUL character (\u0000), Backspace (\u0008), Horizontal tab (\u0009), Newline (\u000A),
Vertical tab (\u000B), Form feed (\u000C),\r Carriage return (\u000D), Double quote (\u0022),
Apostrophe or single quote (\u0027), and Backslash (\u005C)?:-

A

\0, \b, \t, \n, \v, \f, \r, ", ', \

38
Q

38) What comparizon operation can be done on strings?:-

A

Strings can be compare with the standard ‘===’
equality and ‘!==’inequality operations. Two strings are equal if and only if they consit of the same
sequence of 16-bit values.
* Strings can also be compared using the <, <=, >, and >= operators. (here also the comparise is on the sequence
of 16-bit values. Locale-aware comprisons and sorting are done using other methods.)
* length of a String (the number of 16-bit sequence values it contains) is done by ‘string.length’
* Strings can also be treated like read-only arrays, and you can access individual char‐ acters (16-bit values)
from a string using square brackets instead of the charAt() method:
let s = “hello, world”;
s[0] // => “h”
s[s.length-1] // => “d”

39
Q

39) JavaScript provides a rich API for working with strings. What are some of its properties?:-

A

let s = “Hello, world”;
// Obtaining portions of a string
s.substring(1,4) // => “ell”: the 2nd, 3rd, and 4th characters.
s.slice(1,4) // => “ell”: same thing
s.slice(-3) // => “rld”: last 3 characters
s.split(“, “) // => [“Hello”, “world”]: split at delimiter string

// Searching a string
s.indexOf(“l”) // => 2: position of first letter l
s.indexOf(“l”, 3) // => 3: position of first “l” at or after 3
s.indexOf(“zz”) // => -1: s does not include the substring “zz”
s.lastIndexOf(“l”) // => 10: position of last letter l

// Miscellaneous string methods
s.concat(“!”) // => “Hello, world!”: just use + operator instead “<>”.repeat(5)
// => “<><><><><>”: concatenate n copies. ES6

40
Q

40) Given the string let s = “Hello, world”; what do the following properties do; s.startsWith(“Hell”),
s.endsWith(“!”), s.includes(“or”)(// Boolean searching functions in ES6 and later)?:-

A

// => true: the string starts with these
// => false: s does not end with that
// => true: s includes substring “or”

41
Q

41) Given the string let s = “Hello, world”; what do the following properties do; s.replace(“llo”, “ya”), s.toLowerCase()
s.toUpperCase(), s.normalize(), s.normalize(“NFD”) (// Creating modified versions of a string)?:-

A

// => “Heya, world”
// => “hello, world”
// => “HELLO, WORLD”
// Unicode NFC normalization: ES6
// NFD normalization. Also “NFKC”, “NFKD”

  • Remember that strings are immutable in JavaScript.
    Methods like replace() and toUpperCase() return new strings: they do not modify the string on which they are invoked.
42
Q

42) Given the string let s = “Hello, world”; what do the following properties do; s.charAt(0), s.charAt(s.length-1)
s.charCodeAt(0), s.codePointAt(0)(// Inspecting individual (16-bit) characters of a string)?:-

A

// => “H”: the first character
// => “d”: the last character
// => 72: 16-bit number at the specified position
// => 72: ES6, works for codepoints > 16 bits

43
Q

43) What do the following string(add in ES2017) padding functions do; “x”.padStart(3), “x”.padEnd(3),
“x”.padStart(3, “*”), “x”.padEnd(3, “-“)?:-

A

// => “ x”: add spaces on the left to a length of 3
// => “x “: add spaces on the right to a length of 3
// => “**x”: add stars on the left to a length of 3
// => “x–”: add dashes on the right to a length of 3

44
Q

44)what do the Space trimming functions do; “ test “.trim(), “ test “.trimStart(),” test “.trimEnd()
(trim() is ES5; others ES2019)?:-

A

// => “test”: remove spaces at start and end
// => “test “: remove spaces on left. Also trimLeft
// => “ test”: remove spaces at right. Also trimRight

45
Q

45) What is the syntax of a template literal?:-

A

let name = “Scott”;
let greetings = Hello ${name}.; // greeting == “Hello Scott.”

46
Q

46) In javaScript, what does the RegExp type do?:-

A

RegExp(regular expression) is a datatype define by javaScript
for describing, and matching patterns in strings of text.

47
Q

47) What constitutes a RegExp literal?:-

A

Text between two slashes constitutes a regular expression literal.
* The second slash in the pair can also be followed by one or more letters, which modify the meaning of the pattern.
For example:

/^HTML/; // Match the letters H T M L at the start of a string
/[1-9][0-9]*/; // Match a nonzero digit, followed by any # of digits
/\bjavascript\b/i; // Match “javascript” as a word, case-insensitive

48
Q

48) RegExp objects define a number of useful methods, and strings also have methods that accept RegExp arguments.
Name some examples?:-

A

let text = “testing: 1, 2, 3”; // Sample text
let pattern = /\d+/g; // Matches all instances of one or more digits
pattern.test(text) // => true: a match exists
text.search(pattern) // => 9: position of first match
text.match(pattern) // => [“1”, “2”, “3”]: array of all matches
text.replace(pattern, “#”) // => “testing: #, #, #”
text.split(/\D+/) // => [””,”1”,”2”,”3”]: split on nondigits

49
Q

49) A boolean value represents?:-

A

truth or falsehood, on or off, yes or no. They only two possible values
of this type. The reserved world true or false evalute to these two values.

50
Q

50) The following values convert to, and therefore work as false(falsy values). Name the six values(Also name true values(truthy values))?:-

A

-> undefined
-> null
-> 0
-> -0 (negative zero)
-> NaN
-> “” (The empty string)

  • All other values, include objects (and arrays) convert to, and work like true.
51
Q

51) What useful boolean method is used to convert it two values to strings “true”,and “false”?:-

A

the toString() method.

52
Q

52) The three important boolean operators are?:-

A

-> && (AND operation)
-> || (OR “”)
-> ! (NOT “”) AKA unary operator

53
Q

53) What is null in javaScript?:-

A

null is a javaScript keyword that evalutes to a special value that is
usual used to indicate the absence of a value.

  • Using the typeof operator on null returns the string “object”, indicating that null can be thought of
    as a special object value that indicates “no object”.
  • In practice, however, null is typically regarded as the sole member of its own type,
    and it can be used to indicate “no value” for numbers and strings as well as objects.
  • I consider undefined to represent a system-level, unexpected, or error-like absence of value and
    null to represent a program-level, normal, or expected absence of value.
    I avoid using null and undefined when I can, but if I need to assign one of these values to
    a variable or property or pass or return one of these values to or from a func‐ tion, I usually use null.
54
Q

54) The undefined represents a deeper kind of absence compared to null. What does it represent?:-

A

-> undefined is the value return by variables that are yet to be initialized,
-> and the value returned when you query the value of an object property or array element that does not exist.
-> The undefined value is also the return value of functions that donot explicitly return a value,
-> and the value of function parameters for which no argument is passed.

  • undefined is a predefined global constant (not a language keyword like null,
    though this is not an important distinction in practice) that is initialized to the undefined value.
  • If you apply the typeof operator to the unde fined value, it returns “undefined”,
    indicating that this value is the sole member of a special type.
  • Despite these differences, null and undefined both indicate an absence of value and
    can often be used interchangeably. The equality operator == considers them to be equal.
    (Use the strict equality operator === to distinguish them.)
55
Q

55) Other than the toString() method what are the other two function related to Symbol and what do theydo?:-

A

-> javaScript defines a Symbol registry. The Symbol.for() function takes a string argument and returns a Symbol value
related to the passed string. If no Symbol is already associated with that string, then a new one is created and
returned; otherwise, the already existing Symbol is returned.
-> That is, the Symbol.for() function is completely different than the Sym bol() function: Symbol() never returns
the same value twice, but Symbol.for() always returns the same value when called with the same string.
The string passed to Symbol.for() appears in the output of toString() for the returned Symbol,
and it can also be retrieved by calling Symbol.keyFor() on the returned Symbol.

let s = Symbol.for(“shared”);
let t = Symbol.for(“shared”);
s === t // => true
s.toString() // => “Symbol(shared)”
Symbol.keyFor(t) // => “shared”e

  • Sometimes when using Symbols, you want to keep them private to your own code so you have a guarantee that
    your properties will never conflict with properties used by other code.
  • Other times, however, you might want to define a Symbol value and share it widely with other code.
    This would be the case, for example, if you were defining some kind of extension that you wanted other
    code to be able to participate in, as with the Symbol.iterator mechanism described earlier.
56
Q

56) What is the javaScript Global Object?:-

A

The global object is a regular javaScript object that serves
a very important purpose: the properties of this object are the globally defined identifiers available to a
javaScript program.

57
Q

57) When the JavaScript interpreter starts (or whenever a web browser loads a new page), it creates a new
global object and gives it an initial set of properties that define?:-

A

-> Global constants like undefined, Infinity,and NaN.
-> Global functions linke isNaN(), parseInt(), and eval().
-> Constructor functions like Date(), RegExp(), Strings(), Objects(), and Arrays().
-> Global objects like Math and JSON

58
Q

58) Objects are not compared by value. What does that mean, given two object (and array) with the same values?:-

A

-> Two distict objects are not equal even if they have the same properties and values in the same order.
-> And two distict arrays are not equal even if they have the same elements in the same order.

let o = {x: 1}, p = {x: 1}; // Two objects with the same properties
o === p // => false: distinct objects are never equal
let a = [],b=[]; // Two distinct, empty arrays
a === b // => false: distinct arrays are never equal

59
Q

59 addd

A

Add

60
Q

60) Two objects are equal if and only if?:-

A

they refer to the same underlying object.

61
Q

61) Why are object types refered to as reference types?:-

A

because object values are references, and that is why
objects are compared by reference and not by value like primitive values.

leta = []; // The variable a refers to an empty array.
let b = a; // Now b refers to the same array.
b[0] = 1; // Mutate the array referred to by variable b.
a[0] // => 1: the change is also visible through variable a.
a === b // => true: a and b refer to the same object, so they are equal.

  • As you can see from this code, assigning an object (or array) to a variable simply assigns the reference:
    it does not create a new copy of the object.
62
Q

62) During javaScript type conversion what do the following values become when converted to String, to Number,
and to Boolean;
undefined
null
true
false
“” (empty string)
“1.2” (nonempty, numeric) “one” (nonempty, non-numeric) 0
-0
1 (finite, non-zero)
Infinity
-Infinity
NaN
{} (any object)
[] (empty array)
[9] (one numeric element)
[‘a’] (any other array)
function(){} (any function) ?:- none is performed

A

VALUE -to String - to Number - to Boolean
undefined - “undefined” - NaN - false
null - “null” - 0 - false
true - “true” - 1 - none
false - “false” - 0 - none
“” (empty string) none - 0 - false
“1.2” (nonempty, numeric) none - 1.2 - true
“one” (nonempty, non-numeric) none - NaN - true
0 “0” - none - false
-0 “0” - none - false
1 (finite, non-zero) - “1” - none - true
Infinity - “Infinity” - none - true
-Infinity - “-Infinity” - none - true
NaN - “NaN” - none - false
{} (any object) - see §3.9.3 - see §3.9.3 - true
[] (empty array) - “” - 0 - true
[9] (one numeric element) - “9” - 9 - true
[‘a’] (any other array) - use join() method - NaN - true
function(){} (any function)- see §3.9.3- NaN - true

63
Q

63) The “strict equal‐ ity operator,” ===, does not consider its operands to be equal if they are not?:-

A

of the same type, and this is almost always the right operator to use when coding.

64
Q

64) The simplest way to perform an explicit type conversion is to use?:-

A

the Boolean(), Num ber(), and String()
functions:
Number(“3”) // => 3
String(false) // => “false”: Or use false.toString()
Boolean([]) // => true

*Any value other than null or undefined has a toString() method, and the result of this method is usually
the same as that returned by the String() function.

65
Q

65) What javaScript operators perform implicit type conversions and conversions and are sometimes used explicitly
for the purpose of type conversion?:-

A

-> If one operand of the + operator is a string, it converts the other one to a string.
-> The unary + operator converts its operand to a number.
-> And the unary ! operator converts its operand to a boolean and negates it.
These facts lead to the following type conversion idioms that you may see in some code:
x + “” // => String(x)
+x // => Number(x)
x-0 // => Number(x)
!!x // => Boolean(x): Note double !

66
Q

66) What does the toString() method defined by Number class do and what optional arguments can be provided?:-

A

it converts numbers to strings. in addition it accepts an optional argument that specifies a radix, or base(
default is base 10) for conversion. However, you can also convert numbers in other bases (between 2 and 36). For example:
let n = 17;
let binary = “0b” + n.toString(2); // binary == “0b10001”
let octal = “0o” + n.toString(8); // octal == “0o21”
let hex = “0x” + n.toString(16); // hex == “0x11”

67
Q

67) When working with financial or scientific data, you may want to convert number to strings in ways that
give you control over the number of decimal places, or the number of significant digits in the output, or you
may want to control whether exponential notation is used. The number class defines methods for these kinds of
number-to-string conversions. Namely?:-

A

-> toFixed() converts a number to a string with specified number of digits after the decimal point.It never
uses exponent notation.
-> toExponential() converts a number to a string using exponential notation, with one digit before the decimal
point and a specified number of digits after the decimal point(Which means the number of significant digits is
one larger than the value you specify).
-> toPrecision() coverts a number to a string with the number of significant digits you specify. It uses
exponential notation if the number of significant digits is not large enough to display the entire integer
portion of the number.

  • Note that all three methods round the trailing digits or pad with zeros as appropriate.
    Consider the following examples:
    let n = 123456.789;
    n.toFixed(0) // => “123457”
    n.toFixed(2) // => “123456.79”
    n.toFixed(5) // => “123456.78900”
    n.toExponential(1) // => “1.2e+5”
    n.toExponential(3) // => “1.235e+5”
    n.toPrecision(4) // => “1.235e+5”
    n.toPrecision(7) // => “123456.8”
    n.toPrecision(10) // => “123456.7890”
68
Q

68) What happens when you pass astring to the Number() conversion function?:-

A

it attempts to parse that string as an integer or floating-point literal. That function only works for base-10 integers and does not allow trailing characters that are not part of the literal.

69
Q

69) parseInt() and parseFloat() functions (these are global functions, not methods of any class) more flexible
compared to Number(). how do they work?:-

A

-> parseInt only parses only intergers. If a string begins with “0x” or “0X”, parseInt() interprets it as
a hexadecimal number.
-> parseFloat parses both floats and integers.
* Both parseInt() and parse Float() skip leading whitespace, parse as many numeric characters as they can,
and ignore anything that follows. If the first nonspace character is not part of a valid numeric literal,
they return NaN:

parseInt(“3 blind mice”) // => 3
parseFloat(“ 3.14 meters”) // => 3.14
parseInt(“-12.34”) // => -12
parseInt(“0xFF”) // => 255
parseInt(“0xff”) // => 255
parseInt(“-0XFF”) // => -255
parseFloat(“.1”) // => 0.1
parseInt(“0.1”) // => 0
parseInt(“.1”) // => NaN: integers can’t start with “.”
parseFloat(“$72.47”) // => NaN: numbers can’t start with “$”

  • parseInt() accepts an optional second argument specifying the radix (base) of the number to be parsed.
    Legal values are between 2 and 36. For example:

parseInt(“11”, 2) // => 3: (12 + 1)
parseInt(“ff”, 16) // => 255: (15
16 + 15)
parseInt(“zz”, 36) // => 1295: (3536 + 35)
parseInt(“077”, 8) // => 63: (7
8 + 7)
parseInt(“077”, 10) // => 77: (7*10 + 7)

70
Q

70) The javaScript specification defines three fundamental algorithms for converting object to primitive values.
name and explain them?:-

A

-> prefer-string. This algorithm returns a primitive value, preferring a string value, if a conversion to string
is possible.
* The prefer-string algorithm first tries the toString() method. If the method is defined and returns a
primitive value, then JavaScript uses that primitive value (even if it is not a string!). If toString() does not
exist or if it returns an object, then JavaScript tries the valueOf() method. If that method exists and returns
a primitive value, then JavaScript uses that value. Otherwise, the conversion fails with a TypeError.
-> prefer-number. This algorithm returns a primitive value, preferring a number, if such a conversion is possible.
* The prefer-number algorithm works like the prefer-string algorithm, except that it tries valueOf() first and
toString() second.
-> no-preference. This algorithm expresses no preference about what type of primitive value is desired,
and classes can define their own conversions. Of the built-in JavaScript types, all except Date implement
this algorithm as prefer-number. The Date class implements this algorithm as prefer-string.
* The no-preference algorithm depends on the class of the object being converted. If the object is a Date object,
then JavaScript uses the prefer-string algorithm. For any other object, JavaScript uses the prefer-number
algorithm.

71
Q

71) Object-to-boolean conversions are trivial, explain?:-

A

all objects convert to true. Notice that this
conversion does not require the use of the object-to-primitive algorithms, and that it literally applies to
all objects, including empty arrays and even the wrapper objectnew Boolean(false).

72
Q

72) How do Object-to-string conversions happen?:-

A

When an object needs to be converted to a string, JavaScript first
converts it to a primitive using the prefer-string algorithm, then converts the resulting primitive value to a string.
* This kind of conversion happens, for example, if you pass an object to a built-in func‐ tion that expects a string
argument, if you call String() as a conversion function, and when you interpolate objects into template literals

73
Q

73) How do Object-to-number conversions happen?:-

A

When an object needs to be converted to a number, JavaScript
first converts it to a primitive value using the prefer-number algorithm, then converts the resulting primitive
value to a number.
* Built-in JavaScript functions and methods that expect numeric arguments convert object arguments to numbers
in this way, and most (see the exceptions that follow) JavaScript operators that expect numeric operands convert
objects to numbers in this way as well.

74
Q

74) The Special case ‘+’ operator conversions. How are they done?:-

A

The + operator in JavaScript performs numeric addition and string concatenation. If either of its operands is
an object, JavaScript converts them to primitive values using the no-preference algorithm. Once it has two
primitive values, it checks their types. If either argument is a string, it converts the other to a string
and concatenates the strings. Otherwise, it converts both arguments to numbers and adds them.

75
Q

75) The Special case ‘==’ and ‘!=’ operators conversions. How are they done?:-

A

The == and != operators perform equality and inequality testing in a loose way that allows type conversions.
If one operand is an object and the other is a primitive value, these operators convert the object to primitive
using the no-preference algorithm and then compare the two primitive values.

76
Q

76) The Special case <, <=, >, and >= operators conversions. How are they done?:-

A

the relational operators <, <=, >, and >= compare the order of their operands and can be used to compare both
numbers and strings. If either operand is an object, it is converted to a primitive value using the prefer-number
algorithm. Note, however, that unlike the object-to-number conversion, the primitive values returned by the
prefer-number conversion are not then converted to numbers.

  • Note that the numeric representation of Date objects is meaningfully comparable with < and >, but the string
    representation is not. For Date objects, the no-preference algorithm converts to a string, so the fact that
    JavaScript uses the prefer-number algorithm for these operators means that we can use them to compare the order
    of two Date objects.
77
Q

77) All objects inherit two conversion methods that are used by object-to-primitive conversions. These methods
help in understanding the prefer-string, prefer-number, and no-preference conversion algorithms. Name the methods?:-

A

-> The first method is toString(), and its job is to return a string representation of the object.
* The default toString() method does not return a very interesting value.
({x: 1, y: 2}).toString() // => “[object Object]”
* Many classes define more specific versions of the toString() method. The toString() method of the Array class,
for example, converts each array element to a string and joins the resulting strings together with commas in
between. The toString() method of the Function class converts user-defined functions to strings of JavaScript
source code. The Date class defines a toString() method that returns a human-readable (and JavaScript-parsable)
date and time string. The RegExp class defines a toString() method that converts RegExp objects to a string
that looks like a RegExp literal:
[1,2,3].toString() // => “1,2,3”
(function(x) { f(x); }).toString() // => “function(x) { f(x); }”
/\d+/g.toString() // => “/\d+/g”
let d = new Date(2020,0,1);
d.toString() // => “Wed Jan 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)”
-> The other object conversion function is called valueOf(). The job of this method is less well defined:
it is supposed to convert an object to a primitive value that repre‐ sents the object, if any such primitive
value exists. Objects are compound values, and most objects cannot really be represented by a single primitive
value, so the default valueOf() method simply returns the object itself rather than returning a primitive.
Wrapper classes such as String, Number, and Boolean define valueOf() methods that simply return the wrapped
primitive value. Arrays, functions, and regular expressions simply inherit the default method. Calling valueOf()
for instances of these types sim‐ ply returns the object itself. The Date class defines a valueOf() method that
returns the date in its internal representation: the number of milliseconds since January 1, 1970:

let d = new Date(2010, 0, 1); // January 1, 2010, (Pacific time)
d.valueOf() // => 1262332800000

78
Q

78) the prefer-number conversion explain why empty arrays convert to the number 0 and single-element
arrays can also convert to numbers:
Number([]) // => 0: this is unexpected!
Number([99]) // => 99: really?
?:-

A

The object-to-number conversion first converts the object to a primitive using the prefer-number algorithm,
then converts the resulting primitive value to a number. The prefer-number algorithm tries valueOf() first
and then falls back on toString(). But the Array class inherits the default valueOf() method, which does not
return a primitive value. So when we try to convert an array to a number, we end up invoking the toString()
method of the array. Empty arrays convert to the empty string. And the empty string converts to the number 0.
An array with a single element converts to the same string that that one element does. If an array contains a
single number, that number is converted to a string, and then back to a number.

79
Q

79) What is a variable?:-

A

The term “variable” implies that new values can be assigned: that the value associated
with the variable may vary as our program runs.
* It is a good programming practice to assign an initial value to your variables when you declare(declared with
let) them, when this is possible:

80
Q

80) If we permanently assign a value to a name, then we call that name?:-

A

constant instead of a variable.
* const works just like let except that you must initialize the constant when you declare it:
* It is a common (but not universal) convention to declare constants using names with all capital letters such
as H0 or HTTP_NOT_FOUND as a way to distinguish them from variables.

81
Q

81) What is the scope of a vairable and a constant?:-

A

Variables and constants declared with let and const are
block scoped(The scope of a variable is the region of your program source code in which it is defined).
* When a declaration appears at the top level, outside of any code blocks, we say it is a global variable or
constant and has global scope. In Node and in client-side JavaScript modules, the scope of a global variable
is the file that it is defined in.

82
Q

82) It is a syntax error to use the same name with more than one let or const declaration in the same scope.
It is legal (though a practice best avoided) to declare a new variable with the same name in a nested scope;
example code?:-

A

const x = 1; // Declare x as a global
constant if (x === 1) {
let x = 2; // Inside a block x can refer to a different value
console.log(x); // Prints 2
}
console.log(x); // Prints 1: we’re back in the global scope now
let x = 3; // ERROR! Syntax error trying to re-declare x

83
Q

83) Although var and let have the same syntax, there are(4) important differences in the way they work?:-

A

-> Variables declared with var do not have block scope. Instead, they are scoped to the body of the containing
function no matter how deeply nested they are inside that function.
-> If you use var outside of a function body, it declares a global variable. But global variables declared with
var differ from globals declared with let in an important way. Globals declared with var are implemented as
properties of the global object.The global object can be referenced as globalThis. So if you write var x = 2;
outside of a function, it is like you wrote globalThis.x = 2;. Note how‐ ever, that the analogy is not perfect:
the properties created with global var decla‐ rations cannot be deleted with the delete operator.
Global variables and constants declared with let and const are not properties of the global object.
->Unlike variables declared with let, it is legal to declare the same variable multiple times with var.
And because var variables have function scope instead of block scope, it is actually common to do this kind of
redeclaration. The variable i is frequently used for integer values, and especially as the index variable of
for loops. In a function with multiple for loops, it is typical for each one to begin for(var i = 0; ….
Because var does not scope these variables to the loop body, each of these loops is (harmlessly) re-declaring
and re-initializing the same variable. )
-> One of the most unusual features of var declarations is known as hoisting. When a variable is declared with
var, the declaration is lifted up (or “hoisted”) to the top of the enclosing function. The initialization of the
variable remains where you wrote it, but the definition of the variable moves to the top of the function.
So variables declared with var can be used, without error, anywhere in the enclosing function.
If the initialization code has not run yet, then the value of the variable may be undefined, but you won’t get
an error if you use the variable before it is initialized. (This can be a source of bugs and is one of the
important misfeatures that let corrects: if you declare a variable with let but attempt to use it before the
let statement runs, you will get an actual error instead of just seeing an undefined value.)

84
Q

84) what is Destructuring Assignment?:-

A

ES6 implements a kind of compound declaration and assignment
syntax known as destructuring assignment.
* In a destructuring assignment, the value on the righthand side of the equals sign is an array or object
(a “structured” value), and the lefthand side specifies one or more variable names using a syntax that mimics
array and object literal syntax.
* When a destructuring assignment occurs, one or more values are extracted (“destructured”) from the value on
the right and stored into the variables named on the left.
* Destructuring assignment is perhaps most commonly used to ini‐ tialize variables as part of a const, let, or
var declaration statement, but it can also be done in regular assignment expressions (with variables that have
already been declared). And, destructuring can also be used when defining the parameters to a function.

Here are simple destructuring assignments using arrays of values:
let [x,y] = [1,2]; // Same as let x=1, y=2
[x,y] = [x+1,y+1]; // Same as x = x + 1, y = y + 1
[x,y] = [y,x]; // Swap the value of the two variables
[x,y] // => [3,2]: the incremented and swapped values

85
Q

85) Destructuring assignment makes it easy to work with functions that return arrays of values: Write simple
functions that Convert [x,y] coordinates to [r,theta] polar coordinates and Convert polar to
Cartesian coordinates?:-

A

// Convert [x,y] coordinates to [r,theta] polar coordinates
function toPolar(x, y) {
return [Math.sqrt(xx+yy), Math.atan2(y,x)];
}
// Convert polar to Cartesian coordinates
function toCartesian(r, theta) {
return [rMath.cos(theta), rMath.sin(theta)];
}

86
Q

86) We saw that variables and constants can be declared as part of JavaScript’s various for loops. It is possible
to use variable destructuring in this context as well. Write code that loops over the name/value pairs of
all properties of an object and uses destructuring assignment to convert those pairs from two-element arrays
into individual variables:

A

let o = { x: 1, y: 2 }; // The object we’ll loop over
for(const [name, value] of Object.entries(o)) {
console.log(name, value); // Prints “x 1” and “y 2”
}

87
Q

87) The number of variables on the left of a destructuring assignment does not have to match the number of array
elements on the right. Extra variables on the left are set to undefined, and extra values on the right are
ignored. The list of variables on the left can include extra commas to skip certain values on the right. Implement
code examples?:-

A

let [x,y] = [1]; // x == 1; y == undefined
[x,y] = [1,2,3]; // x == 1; y == 2
[,x,,y] = [1,2,3,4]; // x == 2; y == 4

88
Q

88) How do you collect all unused or remaining values into a single variable when destructuring an array?:-

A

by using three dots (…) before the last variable name on the left- hand side:
let [x, …y] = [1,2,3,4]; // y == [2,3,4]

89
Q

89) Destructuring assignment can be used with nested arrays. In this case, the lefthand side of the assignment
should look like?:-

A

a nested array literal:
let [a, [b, c]] = [1, [2,2.5], 3]; // a == 1; b == 2; c == 2.5

90
Q

90) A powerful feature of array destructuring is that it does not actually require an array! Explain?:-

A

You can use any iterable object on the righthand side of the assignment; any object that can be used
with a for/of loop can also be destructured:

let [first, …rest] = “Hello”; // first == “H”; rest == [“e”,”l”,”l”,”o”]

91
Q

91) Destructuring assignment can also be performed when the righthand side is an object value. In this case,
the lefthand side of the assignment looks something like?:-

A

an object literal: a comma-separated list of variable names within curly braces:
let transparent = {r: 0.0, g: 0.0, b: 0.0, a: 1.0}; // A RGBA color
let {r, g, b} = transparent; // r == 0.0; g == 0.0; b == 0.0

  • The next example copies global functions of the Math object into variables, which might simplify
    code that does a lot of trigonometry:
    // Same as const sin=Math.sin, cos=Math.cos, tan=Math.tan
    const {sin, cos, tan} = Math;
  • Notice in the code here that the Math object has many properties other than the three that are destructured
    into individual variables. Those that are not named are simply ignored. If the lefthand side of this assignment
    had included a variable whose name was not a property of Math, that variable would simply be assigned undefined.
  • Each of the identifiers on the lefthand side of an object destructuring assignment can also be a
    colon-separated pair of identifiers, where the first is the name of the property whose value is to be assigned
    and the second is the name of the variable to assign it to:
    // Same as const cosine = Math.cos, tangent = Math.tan;
    const { cos: cosine, tan: tangent } = Math;
  • I find that object destructuring syntax becomes too complicated to be useful when the variable names and
    property names are not the same, and I tend to avoid the short‐ hand in this case. If you choose to use it, remember that
    property names are always on the left of the colon, in both object literals and on the left of an object
    destructuring assignment.
92
Q

92) Destructuring assignment becomes even more complicated when it is used with nes‐ ted objects, or arrays of
objects, or objects of arrays, but it is legal. show code example?:-

A

let points = [{x: 1, y: 2}, {x: 3, y: 4}]; // An array of two point objects
let [{x: x1, y: y1}, {x: x2, y: y2}] = points; // destructured into 4 variables.
(x1 === 1 && y1 === 2 && x2 === 3 && y2 === 4) // => true

Or, instead of destructuring an array of objects, we could destructure an object of arrays:

let points = { p1: [1,2], p2: [3,4] }; // An object with 2 array props
let { p1: [x1, y1], p2: [x2, y2] } = points; // destructured into 4 vars
(x1 === 1 && y1 === 2 && x2 === 3 && y2 === 4) // => true

  • Complex destructuring syntax like this can be hard to write and hard to read, and you may be better off just
    writing out your assignments explicitly with traditional code likelet x1 = points.p1[0];.