├── .gitignore ├── code ├── 001 │ └── script.js ├── 005 │ └── script.js ├── 009 │ └── script.js ├── 008 │ └── script.js ├── 041 │ └── script.js ├── 002 │ └── script.js ├── 004 │ └── script.js ├── 021 │ └── script.js ├── 019 │ └── script.js ├── 020 │ └── script.js ├── 027 │ └── script.js ├── 028 │ └── script.js ├── 029 │ └── script.js ├── 006 │ └── script.js ├── 023 │ └── script.js ├── 026 │ └── script.js ├── 030 │ └── script.js ├── 022 │ └── script.js ├── 013 │ └── script.js ├── 007 │ └── script.js ├── 031 │ └── script.js ├── 040 │ ├── script.mjs │ └── module.mjs ├── 039 │ └── script.js ├── 012 │ └── script.js ├── 015 │ └── script.js ├── 003 │ └── script.js ├── 032 │ └── script.js ├── 011 │ └── script.js ├── 024 │ └── script.js ├── 033 │ └── script.js ├── 036 │ └── script.js ├── 018 │ └── script.js ├── 037 │ └── script.js ├── 035 │ └── script.js ├── miscellaneous │ └── 001 │ │ └── script.js ├── 034 │ └── script.js ├── 025 │ └── script.js ├── 014 │ └── script.js ├── 017 │ └── script.js ├── 010 │ └── script.js └── 038 │ └── script.js ├── .husky └── pre-commit ├── .prettierrc ├── package.json ├── LICENSE ├── CODE_OF_CONDUCT.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea 3 | node_modules -------------------------------------------------------------------------------- /code/001/script.js: -------------------------------------------------------------------------------- 1 | console.log(new Date(2023, 0, 31).toDateString()) 2 | -------------------------------------------------------------------------------- /code/005/script.js: -------------------------------------------------------------------------------- 1 | console.log(undefined == null, undefined === null) 2 | -------------------------------------------------------------------------------- /code/009/script.js: -------------------------------------------------------------------------------- 1 | console.log(isFinite(Infinity), isNaN(Infinity)) 2 | -------------------------------------------------------------------------------- /code/008/script.js: -------------------------------------------------------------------------------- 1 | console.log('BG Web Agency' === NaN, isNaN('BG Web Agency')) 2 | -------------------------------------------------------------------------------- /code/041/script.js: -------------------------------------------------------------------------------- 1 | // foo.js 2 | function foo() { 3 | console.log(`Foo`) 4 | } 5 | export { foo } 6 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | npx pretty-quick --staged 5 | -------------------------------------------------------------------------------- /code/002/script.js: -------------------------------------------------------------------------------- 1 | var username = 'kirandash' 2 | var username = 'bgwebagency' 3 | 4 | console.log(username) 5 | -------------------------------------------------------------------------------- /code/004/script.js: -------------------------------------------------------------------------------- 1 | const len1 = 'kiran'.length 2 | const len2 = '👻'.length 3 | 4 | console.log(len1, len2) 5 | -------------------------------------------------------------------------------- /code/021/script.js: -------------------------------------------------------------------------------- 1 | const myArray = [1, 2, 3, 4, 5] 2 | const poppedValue = myArray.pop() 3 | console.log(poppedValue) 4 | -------------------------------------------------------------------------------- /code/019/script.js: -------------------------------------------------------------------------------- 1 | let arr = [1, 2, 3, 4] 2 | let result = arr.push(5) 3 | console.log('result: ', result, 'arr: ', arr) 4 | -------------------------------------------------------------------------------- /code/020/script.js: -------------------------------------------------------------------------------- 1 | let arr = [3, 5, 7, 9] 2 | let result = arr.unshift(1, 2) 3 | console.log('result: ', result, 'arr: ', arr) 4 | -------------------------------------------------------------------------------- /code/027/script.js: -------------------------------------------------------------------------------- 1 | const numbers = [1, 2, 3, 4, 5] 2 | const sum = numbers.reduce((acc, val) => acc + val) 3 | console.log(sum) 4 | -------------------------------------------------------------------------------- /code/028/script.js: -------------------------------------------------------------------------------- 1 | const arr = [1, 2, 3, 4] 2 | const result = arr.reduceRight((acc, curr) => acc + curr) 3 | console.log(result) 4 | -------------------------------------------------------------------------------- /code/029/script.js: -------------------------------------------------------------------------------- 1 | const arr = ['Centauri', undefined, 3.14159, 'canine', 11235] 2 | const result = arr.sort() 3 | console.log(result) 4 | -------------------------------------------------------------------------------- /code/006/script.js: -------------------------------------------------------------------------------- 1 | function getFruits(x, y, ...multi) { 2 | console.log(x, y, multi) 3 | } 4 | getFruits('🍎', '🍌', '🍇', '🍊', '🍍') 5 | -------------------------------------------------------------------------------- /code/023/script.js: -------------------------------------------------------------------------------- 1 | let arr = [1, 2, 3, 4, 5] 2 | let removed = arr.splice(1, 2, 'a', 'b') 3 | onsole.log('removed:', removed, 'arr: ', arr) 4 | -------------------------------------------------------------------------------- /code/026/script.js: -------------------------------------------------------------------------------- 1 | const numbers = [1, 2, 3, 4, 5] 2 | const doubledNumbers = numbers.map(num => num * 2) 3 | console.log(doubledNumbers) 4 | -------------------------------------------------------------------------------- /code/030/script.js: -------------------------------------------------------------------------------- 1 | let numbers = [1, 2, 3, undefined, 6, 7, 8, 9] 2 | 3 | let [a, , b, c = 2, ...rest] = numbers 4 | 5 | console.log(a, b, c, rest) 6 | -------------------------------------------------------------------------------- /code/022/script.js: -------------------------------------------------------------------------------- 1 | const arr = [10, 20, 30, 40, 50] 2 | const removedElement = arr.shift() 3 | console.log('removedElement: ', removedElement, 'arr: ', arr) 4 | -------------------------------------------------------------------------------- /code/013/script.js: -------------------------------------------------------------------------------- 1 | function multiply(x) { 2 | return function (y) { 3 | return x * y 4 | } 5 | } 6 | 7 | const double = multiply(2) 8 | 9 | console.log(double(5)) 10 | -------------------------------------------------------------------------------- /code/007/script.js: -------------------------------------------------------------------------------- 1 | let x = Number.NEGATIVE_INFINITY // Infinity 2 | let y = Number.POSITIVE_INFINITY // -Infinity 3 | let z = x + y // NaN 4 | console.info(x, y) 5 | console.log(z) 6 | -------------------------------------------------------------------------------- /code/031/script.js: -------------------------------------------------------------------------------- 1 | const date1 = new Date() 2 | const date2 = new Date('1995-12-17T05:10:00') 3 | const date3 = new Date('1995-10-15T08:12:15+02:00') 4 | 5 | console.log(date1, '', date2, '', date3) 6 | -------------------------------------------------------------------------------- /code/040/script.mjs: -------------------------------------------------------------------------------- 1 | import calculateCircumference, { PI, calculateArea } from './module.mjs'; 2 | 3 | console.log(PI); 4 | console.log(calculateArea(5)); 5 | console.log(calculateCircumference(5)); 6 | -------------------------------------------------------------------------------- /code/039/script.js: -------------------------------------------------------------------------------- 1 | const person = { 2 | name: 'John', 3 | age: 30, 4 | city: 'New York', 5 | } 6 | 7 | const { name, age, city } = person 8 | 9 | console.log(name) 10 | console.log(age) 11 | console.log(city) 12 | -------------------------------------------------------------------------------- /code/012/script.js: -------------------------------------------------------------------------------- 1 | function add(x) { 2 | return function (y) { 3 | if (y !== undefined) { 4 | x += y 5 | return arguments.callee 6 | } else { 7 | return x 8 | } 9 | } 10 | } 11 | 12 | console.log(add(1)(2)(3)()) 13 | -------------------------------------------------------------------------------- /code/040/module.mjs: -------------------------------------------------------------------------------- 1 | export const PI = 3.14159; 2 | 3 | export function calculateArea(radius) { 4 | return PI * radius * radius; 5 | } 6 | 7 | export default function calculateCircumference(radius) { 8 | return 2 * PI * radius; 9 | } -------------------------------------------------------------------------------- /code/015/script.js: -------------------------------------------------------------------------------- 1 | function* counter() { 2 | let i = 0 3 | while (true) { 4 | yield i++ 5 | } 6 | } 7 | 8 | const gen = counter() 9 | 10 | console.log(gen.next().value) 11 | console.log(gen.next().value) 12 | console.log(gen.next().value) 13 | -------------------------------------------------------------------------------- /code/003/script.js: -------------------------------------------------------------------------------- 1 | // update username for user with arrow function 2 | const user = { 3 | username: 'kirandash', 4 | updateUsername: newName => { 5 | this.username = newName 6 | }, 7 | } 8 | 9 | user.updateUsername('bgwebagency') 10 | console.log(user.username) 11 | -------------------------------------------------------------------------------- /code/032/script.js: -------------------------------------------------------------------------------- 1 | const date = new Date('Mart 15, 1975 23:15:30') 2 | date.setMinutes(10) 3 | date.setUTCDate(5) 4 | 5 | console.log( 6 | 'Minutes:' + date.getMinutes() + ',', 7 | '', 8 | 'Year:' + date.getFullYear() + ',', 9 | '', 10 | 'UTCDate:' + date.getUTCDate(), 11 | ) 12 | -------------------------------------------------------------------------------- /code/011/script.js: -------------------------------------------------------------------------------- 1 | // PROBLEM 2 | for (var i = 0; i < 3; i++) { 3 | setTimeout(function () { 4 | console.log(i) 5 | }, 0) 6 | } 7 | 8 | // SOLUTION 9 | for (var i = 0; i < 3; i++) { 10 | ;(function (j) { 11 | setTimeout(function () { 12 | console.log(j) 13 | }, 0) 14 | })(i) 15 | } 16 | -------------------------------------------------------------------------------- /code/024/script.js: -------------------------------------------------------------------------------- 1 | const fruits = ['apple', 'banana', 'orange', 'grape', 'apple', 'kiwi'] 2 | const index = fruits.indexOf('orange') 3 | const lastIndex = fruits.lastIndexOf('apple') 4 | const result = fruits.includes('grape') 5 | console.log('index: ', index, 'lastIndex: ', lastIndex, 'result: ', result) 6 | -------------------------------------------------------------------------------- /code/033/script.js: -------------------------------------------------------------------------------- 1 | const date1 = new Date('2023-5-1') 2 | const next_us_election = new Date('2024-11-5') 3 | const difference_in_time = next_us_election.getTime() - date1.getTime() 4 | const difference_in_days = difference_in_time / (1000 * 3600 * 24) 5 | console.log(parseInt(difference_in_days, 10) + ' Days') 6 | -------------------------------------------------------------------------------- /code/036/script.js: -------------------------------------------------------------------------------- 1 | function greet(name) { 2 | console.log(`Hello, ${name}! Welcome to ${this.location}.`) 3 | } 4 | 5 | const person = { 6 | location: 'New York', 7 | } 8 | 9 | greet.call(person, 'John') 10 | greet.apply(person, ['Alex']) 11 | const greetPerson = greet.bind(person) 12 | greetPerson('Thomas') 13 | -------------------------------------------------------------------------------- /code/018/script.js: -------------------------------------------------------------------------------- 1 | const arr = [1, 2, 3, 4, 5] 2 | let sum = 0 3 | for (let num of arr) { 4 | sum += num 5 | if (sum >= 6) break 6 | } 7 | console.log(sum) 8 | 9 | const arr2 = [1, 2, 3, 4, 5] 10 | let sum2 = 0 11 | arr.forEach(num => { 12 | sum2 += num 13 | // if(sum2 >= 6) break; 14 | }) 15 | console.log(sum2) 16 | -------------------------------------------------------------------------------- /code/037/script.js: -------------------------------------------------------------------------------- 1 | class Animal { 2 | constructor(name) { 3 | this.name = name 4 | } 5 | static makeSound() { 6 | console.log('Generic animal sound') 7 | } 8 | sayName() { 9 | console.log(`My name is ${this.name}`) 10 | } 11 | } 12 | 13 | const a1 = new Animal('Lion') 14 | const a2 = new Animal('Time') 15 | 16 | Animal.makeSound() 17 | a1.makeSound() 18 | a2.makeSound() 19 | -------------------------------------------------------------------------------- /code/035/script.js: -------------------------------------------------------------------------------- 1 | function User(username) { 2 | this.username = username 3 | 4 | this.updateUsername = newName => { 5 | this.username = newName 6 | } 7 | } 8 | 9 | const user1 = new User('kirandash') 10 | const user2 = new User('bgwebagency') 11 | 12 | user1.updateUsername('kirandash-website') 13 | user2.updateUsername('bgwebagency-app') 14 | 15 | console.log(user1.username, user2.username) 16 | -------------------------------------------------------------------------------- /code/miscellaneous/001/script.js: -------------------------------------------------------------------------------- 1 | function replacer(key, value) { 2 | if (typeof value === 'Date') { 3 | return value.toJSON() 4 | } else if (typeof value === 'RegExp') { 5 | return value.toString() 6 | } else { 7 | return value 8 | } 9 | } 10 | 11 | const object = { 12 | date: new Date(), 13 | regex: /some regex/, 14 | } 15 | 16 | const jsonString = JSON.stringify(object, replacer) 17 | console.log(jsonString) 18 | -------------------------------------------------------------------------------- /code/034/script.js: -------------------------------------------------------------------------------- 1 | let person = { 2 | name: 'John', 3 | age: 30, 4 | hobbies: ['reading', 'traveling', 'cooking'], 5 | address: { 6 | street: '123 Main St', 7 | city: 'New York', 8 | state: 'NY', 9 | }, 10 | sayHello: function () { 11 | console.log('Hello, my name is ' + this.name) 12 | }, 13 | } 14 | 15 | console.log(person.name) 16 | console.log(person.hobbies[1]) 17 | console.log(person.address.city) 18 | 19 | person.sayHello() 20 | -------------------------------------------------------------------------------- /code/025/script.js: -------------------------------------------------------------------------------- 1 | function isDivisibleBy7(num) { 2 | return num % 7 == 0 3 | } 4 | 5 | const nums = [28, 7, 3, 29, 15, 1, 2, 23] 6 | const filterResult = nums.filter(isDivisibleBy7) 7 | const findResult = nums.find(num => num < 10) 8 | const findIndexResult = nums.findIndex(num => num / 2 == 14) 9 | 10 | console.log( 11 | 'filterResult:', 12 | filterResult, 13 | 'findResult:', 14 | findResult, 15 | 'findIndexResult:', 16 | findIndexResult, 17 | ) 18 | -------------------------------------------------------------------------------- /code/014/script.js: -------------------------------------------------------------------------------- 1 | // Define an object with a custom iterator 2 | const myIterable = { 3 | values: [1, 2, 3, 4, 5], 4 | [Symbol.iterator]() { 5 | let i = 0 6 | return { 7 | next: () => { 8 | if (i >= this.values.length) { 9 | return { value: undefined, done: true } 10 | } else { 11 | return { value: this.values[i++], done: false } 12 | } 13 | }, 14 | } 15 | }, 16 | } 17 | 18 | // Use a for...of loop to iterate over the iterable 19 | for (const value of myIterable) { 20 | console.log(value) 21 | } 22 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "avoid", 3 | "bracketSameLine": false, 4 | "bracketSpacing": true, 5 | "embeddedLanguageFormatting": "auto", 6 | "endOfLine": "lf", 7 | "htmlWhitespaceSensitivity": "css", 8 | "insertPragma": false, 9 | "jsxSingleQuote": false, 10 | "printWidth": 80, 11 | "proseWrap": "always", 12 | "quoteProps": "as-needed", 13 | "requirePragma": false, 14 | "semi": false, 15 | "singleAttributePerLine": false, 16 | "singleQuote": true, 17 | "tabWidth": 2, 18 | "trailingComma": "all", 19 | "useTabs": true 20 | } 21 | -------------------------------------------------------------------------------- /code/017/script.js: -------------------------------------------------------------------------------- 1 | function getData() { 2 | return new Promise((resolve, reject) => { 3 | setTimeout(() => { 4 | resolve('Data retrieved successfully') 5 | }, 1000) 6 | }) 7 | } 8 | 9 | async function main() { 10 | try { 11 | const data = await getData() 12 | console.log(data) 13 | throw new Error('Something went wrong') 14 | } catch (err) { 15 | console.log('Caught an error:', err.message) 16 | return 'Error occurred' 17 | } finally { 18 | console.log('Finally block executed.') 19 | return 'Finally block value' 20 | } 21 | } 22 | 23 | console.log(main()) 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "who-wants-to-be-a-javascriptaire", 3 | "version": "1.0.0", 4 | "description": "JavaScript multiple choice questions with answers and video explanation to help you with Frontend/Web coding interviews", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "prettier": "prettier --write \"**/*.js\"", 9 | "check-format": "prettier --list-different \"**/*.js\"", 10 | "format": "npm run prettier" 11 | }, 12 | "keywords": [], 13 | "author": "", 14 | "license": "ISC", 15 | "devDependencies": { 16 | "husky": "^8.0.3", 17 | "prettier": "^2.8.8", 18 | "pretty-quick": "3.1.3" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /code/010/script.js: -------------------------------------------------------------------------------- 1 | console.log('==== PROBLEM ====') 2 | const user = { 3 | name: 'John', 4 | age: 30, 5 | getName: () => { 6 | return this.name 7 | }, 8 | getAge: function () { 9 | return this.age 10 | }, 11 | } 12 | 13 | const getName = user.getName 14 | const getAge = user.getAge 15 | 16 | console.log(getName()) 17 | console.log(getAge()) 18 | 19 | console.log('==== SOLUTION ====') 20 | const user2 = { 21 | name: 'John', 22 | age: 30, 23 | getName: function () { 24 | // change arrow function to regular function 25 | return this.name 26 | }, 27 | getAge: function () { 28 | return this.age 29 | }, 30 | } 31 | 32 | // do not assign the function to a variable 33 | console.log(user2.getName()) 34 | console.log(user2.getAge()) 35 | -------------------------------------------------------------------------------- /code/038/script.js: -------------------------------------------------------------------------------- 1 | function Animal(name) { 2 | this.name = name 3 | } 4 | 5 | Animal.prototype.eat = function () { 6 | console.log(this.name + ' is eating.') 7 | } 8 | 9 | function Dog(name) { 10 | Animal.call(this, name) 11 | } 12 | 13 | Dog.prototype = Object.create(Animal.prototype) 14 | Dog.prototype.constructor = Dog 15 | 16 | Dog.prototype.bark = function () { 17 | console.log(this.name + ' is barking.') 18 | } 19 | 20 | function CustomArray() { 21 | Array.call(this) 22 | } 23 | 24 | CustomArray.prototype = Object.create(Array.prototype) 25 | CustomArray.prototype.constructor = CustomArray 26 | 27 | CustomArray.prototype.sum = function () { 28 | return this.reduce((acc, val) => acc + val, 0) 29 | } 30 | 31 | var dog = new Dog('Buddy') 32 | dog.eat() 33 | dog.bark() 34 | 35 | var numbers = new CustomArray() 36 | numbers.push(1, 2, 3, 4, 5) 37 | console.log(numbers.sum()) 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2023 BG Web Agency 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributor Covenant Code of Conduct 3 | 4 | ## Our Pledge 5 | 6 | We as members, contributors, and leaders pledge to make participation in our 7 | community a harassment-free experience for everyone, regardless of age, body 8 | size, visible or invisible disability, ethnicity, sex characteristics, gender 9 | identity and expression, level of experience, education, socio-economic status, 10 | nationality, personal appearance, race, caste, color, religion, or sexual 11 | identity and orientation. 12 | 13 | We pledge to act and interact in ways that contribute to an open, welcoming, 14 | diverse, inclusive, and healthy community. 15 | 16 | ## Our Standards 17 | 18 | Examples of behavior that contributes to a positive environment for our 19 | community include: 20 | 21 | * Demonstrating empathy and kindness toward other people 22 | * Being respectful of differing opinions, viewpoints, and experiences 23 | * Giving and gracefully accepting constructive feedback 24 | * Accepting responsibility and apologizing to those affected by our mistakes, 25 | and learning from the experience 26 | * Focusing on what is best not just for us as individuals, but for the overall 27 | community 28 | 29 | Examples of unacceptable behavior include: 30 | 31 | * The use of sexualized language or imagery, and sexual attention or advances of 32 | any kind 33 | * Trolling, insulting or derogatory comments, and personal or political attacks 34 | * Public or private harassment 35 | * Publishing others' private information, such as a physical or email address, 36 | without their explicit permission 37 | * Other conduct which could reasonably be considered inappropriate in a 38 | professional setting 39 | 40 | ## Enforcement Responsibilities 41 | 42 | Community leaders are responsible for clarifying and enforcing our standards of 43 | acceptable behavior and will take appropriate and fair corrective action in 44 | response to any behavior that they deem inappropriate, threatening, offensive, 45 | or harmful. 46 | 47 | Community leaders have the right and responsibility to remove, edit, or reject 48 | comments, commits, code, wiki edits, issues, and other contributions that are 49 | not aligned to this Code of Conduct, and will communicate reasons for moderation 50 | decisions when appropriate. 51 | 52 | ## Scope 53 | 54 | This Code of Conduct applies within all community spaces, and also applies when 55 | an individual is officially representing the community in public spaces. 56 | Examples of representing our community include using an official e-mail address, 57 | posting via an official social media account, or acting as an appointed 58 | representative at an online or offline event. 59 | 60 | ## Enforcement 61 | 62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 63 | reported to the community leaders responsible for enforcement at 64 | [kirankdash](https://twitter.com/kirankdash). 65 | All complaints will be reviewed and investigated promptly and fairly. 66 | 67 | All community leaders are obligated to respect the privacy and security of the 68 | reporter of any incident. 69 | 70 | ## Enforcement Guidelines 71 | 72 | Community leaders will follow these Community Impact Guidelines in determining 73 | the consequences for any action they deem in violation of this Code of Conduct: 74 | 75 | ### 1. Correction 76 | 77 | **Community Impact**: Use of inappropriate language or other behavior deemed 78 | unprofessional or unwelcome in the community. 79 | 80 | **Consequence**: A private, written warning from community leaders, providing 81 | clarity around the nature of the violation and an explanation of why the 82 | behavior was inappropriate. A public apology may be requested. 83 | 84 | ### 2. Warning 85 | 86 | **Community Impact**: A violation through a single incident or series of 87 | actions. 88 | 89 | **Consequence**: A warning with consequences for continued behavior. No 90 | interaction with the people involved, including unsolicited interaction with 91 | those enforcing the Code of Conduct, for a specified period of time. This 92 | includes avoiding interactions in community spaces as well as external channels 93 | like social media. Violating these terms may lead to a temporary or permanent 94 | ban. 95 | 96 | ### 3. Temporary Ban 97 | 98 | **Community Impact**: A serious violation of community standards, including 99 | sustained inappropriate behavior. 100 | 101 | **Consequence**: A temporary ban from any sort of interaction or public 102 | communication with the community for a specified period of time. No public or 103 | private interaction with the people involved, including unsolicited interaction 104 | with those enforcing the Code of Conduct, is allowed during this period. 105 | Violating these terms may lead to a permanent ban. 106 | 107 | ### 4. Permanent Ban 108 | 109 | **Community Impact**: Demonstrating a pattern of violation of community 110 | standards, including sustained inappropriate behavior, harassment of an 111 | individual, or aggression toward or disparagement of classes of individuals. 112 | 113 | **Consequence**: A permanent ban from any sort of public interaction within the 114 | community. 115 | 116 | ## Attribution 117 | 118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 119 | version 2.1, available at 120 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 121 | 122 | Community Impact Guidelines were inspired by 123 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 124 | 125 | For answers to common questions about this code of conduct, see the FAQ at 126 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at 127 | [https://www.contributor-covenant.org/translations][translations]. 128 | 129 | [homepage]: https://www.contributor-covenant.org 130 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 131 | [Mozilla CoC]: https://github.com/mozilla/diversity 132 | [FAQ]: https://www.contributor-covenant.org/faq 133 | [translations]: https://www.contributor-covenant.org/translations 134 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
52 | 53 | #### Answer: C 54 | 55 | In JavaScript, while constructing dates using Date objects months are 0 based. 56 | Which means 0 is for January and 1 is for February. 57 | 58 | So, in this case we are asking JavaScript to set a date of 2023 February 31st 59 | which does not exist. 60 | 61 | But instead of throwing error JavaScript will overflow it to the next month 62 | which is March. 63 | 64 | And since February in 2023 has only 28 days, the code will overflow by 3 days 65 | making the result to be 3rd March 2023. 66 | 67 |
68 |88 | 89 | #### Answer: A 90 | 91 | We can declare the same variable multiple times using the `var` keyword. And the 92 | variable will hold the value which it was assigned in the end. 93 | 94 | But we can not declare the same variable multiple times using `let` or `const` 95 | 96 |
97 |122 | 123 | #### Answer: C 124 | 125 | Because the `updateUsername` function is not working properly and is failing to 126 | update the `username` of the `user`. 127 | 128 | The `updateUsername` function in user `object` is an arrow function, and is not 129 | bound to the `user` object. 130 | 131 | So, the `this` keyword inside updateUsername function is not referring to the 132 | `user` object, but refers to the global scope. 133 | 134 | To fix this issue, we should change the arrow function to a normal function. 135 | 136 |
137 |157 | 158 | #### Answer: A 159 | 160 | In JavaScript, the string length property returns the number of bytes and not 161 | the number of characters like we expect. 162 | 163 | An emoji is a unicode character which is encoded in two bytes. Therefore the 164 | answer is 2 for this question. 165 | 166 | The string length for `kiran` returns `5` because in a string each character is 167 | 1 byte. 168 | 169 |
170 |187 | 188 | #### Answer: B 189 | 190 | First let me explain the difference between equal and strict equal operator. 191 | 192 | The equal operator only checks if both the values are equal. The strict equal 193 | operator checks if both value and type are equal. 194 | 195 | So in this code, the first statement `undefined == null` returns `true` since 196 | both `undefined` and `null` have the same value which is empty. 197 | 198 | But the second statement `undefined === null` returns `false`. Since 199 | `typeof undefined` is `undefined`, whereas `typeof null` is an `object`. 200 | 201 | You might be wondering, why `typeof null` is an `object` when `null` is 202 | basically a primitive data type. This basically is a mistake in JavaScript since 203 | the beginning. 204 | 205 | Now, one more tip for you: when you want to set an empty value for a variable 206 | use `null` instead of `undefined`. Since `undefined` is mainly used to check if 207 | a variable has no value assigned to it. 208 | 209 |
210 |228 | 229 | #### Answer: B 230 | 231 | Rest operators were added as a part of ES6 feature. 232 | 233 | It takes all the arguments passed to a function and puts it in an array. 234 | 235 | If multiple arguments are passed to a function then rest operator must come at 236 | the end. That's why this code snippet will throw an error. 237 | 238 | To fix this issue, please move the rest operator to the end and then it should 239 | work. 240 | 241 |
242 |262 | 263 | #### Answer: C 264 | 265 | NEGATIVE_INFINITY and POSITIVE_INFINITY are properties of the Number object in 266 | JavaScript that represents the mathematical concept of negative infinity and 267 | positive infinity. 268 | 269 | When you add Number.NEGATIVE_INFINITY and Number.POSITIVE_INFINITY, the result 270 | is NaN. 271 | 272 | Adding a positive infinite value to a negative infinite value does not result in 273 | a meaningful numerical value. 274 | 275 | So in this case, z will be NaN. 276 | 277 | Note that the code will not throw a TypeError, as JavaScript is able to perform 278 | the addition operation between Number.NEGATIVE_INFINITY and 279 | Number.POSITIVE_INFINITY. 280 | 281 |
282 |299 | 300 | #### Answer: B 301 | 302 | Using ` === NaN` to check if a value is a number will not work. 303 | 304 | In JavaScript, `NaN` (Not a Number) is a special value that represents an 305 | invalid number. 306 | 307 | NaN is not equal to anything, including itself, so the expression 308 | `"BG Web Agency" === NaN` will always return `false`. 309 | 310 | To check if a value is a number in JavaScript, you can use the `isNaN()` 311 | function. This function returns `true` if the argument passed to it is `NaN`, or 312 | if it cannot be converted to a number. 313 | 314 |
315 |332 | 333 | #### Answer: A 334 | 335 | The `isFinite()` function is used to determine whether a given value is a finite 336 | number. 337 | 338 | It returns false if the value is NaN, Infinity, or -Infinity, and true if the 339 | value is a finite number. 340 | 341 | So, in this example `isFinite(Infinity)` will return false because Infinity is 342 | not a finite number. 343 | 344 | On the other hand, the isNaN() function is used to determine whether a given 345 | value is not a number (NaN). 346 | 347 | It returns true if the value is NaN, and false if the value is a number or any 348 | other data type. 349 | 350 | So, in this example `isNaN(Infinity)` will also return false because Infinity is 351 | not NaN. 352 | 353 | Therefore always use `isFinite` function instead of `isNaN` function when you 354 | want to validate if a number is finite 355 | 356 |
357 |389 | 390 | #### Answer: A 391 | 392 | The `getName` arrow function uses `this` keyword to refer to the object's name 393 | property, but because arrow functions have a lexical `this` binding, the value 394 | of `this` keyword inside the arrow function will be the global object which is 395 | `window` in a browser, or `global` in Node.js. 396 | 397 | Since there is no name property on the `global` object, the function returns 398 | `undefined`. 399 | 400 | The `getAge` function uses a regular function expression and correctly refers to 401 | the age property of the `user` object using `this` keyword. 402 | 403 | But when `getAge` is assigned to the `getAge` variable, it loses the reference 404 | to the `user` object, so when the function is called using `getAge()`, this will 405 | refer to the global object again, and since there is no age property on the 406 | global object, the function returns undefined. 407 | 408 |
409 |430 | 431 | #### Answer: B 432 | 433 | A closure is a function that retains access to variables in its outer scope, 434 | even after the outer function has returned. 435 | 436 | In this example, the answer is B, because the setTimeout function is 437 | asynchronous and does not execute immediately. 438 | 439 | By the time the callback function passed to setTimeout is executed, the loop has 440 | already completed and the i variable has a value of 3. 441 | 442 | Therefore, each call to console.log(i) inside the callback function will 443 | print 3. 444 | 445 | To solve this problem and print 0, 1, 2, we can use an IIFE (Immediately Invoked 446 | Function Expression) to create a new scope for each iteration of the loop. 447 | 448 | This creates a new variable j inside each IIFE, with its own copy of the current 449 | value of i at that iteration of the loop. 450 | 451 | When the callback function passed to setTimeout is executed, it has access to 452 | the j variable in its closure, which has the expected value of 0, 1, or 2 for 453 | each iteration of the loop. 454 | 455 |
456 |484 | 485 | #### Answer: A 486 | 487 | The correct answer is A. The code defines a add function that takes a single 488 | argument x and returns another function that takes a single argument y. 489 | 490 | This inner function checks if y is defined. If it is defined, it adds y to x and 491 | returns a reference to itself using the arguments.callee property, which allows 492 | the function to be called recursively with the next argument. 493 | 494 | If y is not defined, it returns the current value of x. 495 | 496 | Then, the code calls add(1)(2)(3)(). This first calls add(1) with 1 as its 497 | argument, which returns a function that takes a single argument y. 498 | 499 | Then, it calls this function with 2 as its argument, which adds 2 to 1 and 500 | returns a reference to the function. 501 | 502 | Finally, it calls this function with 3 as its argument, which adds 3 to 3 and 503 | returns a reference to the function. 504 | 505 | Since no argument is passed in the last call, it returns the current value of x, 506 | which is 6. 507 | 508 | This code demonstrates a more complex example of currying in JavaScript, where 509 | the curried function returns a reference to itself, allowing it to be called 510 | recursively with the next argument. 511 | 512 |
513 |538 | 539 | #### Answer: B 540 | 541 | The correct answer is B. The code defines a multiply function that takes a 542 | single argument x and returns another function that takes a single argument y. 543 | This inner function multiplies x and y and returns the result. 544 | 545 | Then, the code creates a new function double by calling multiply with 2 as its 546 | argument. The double function is now a curried function that can be called with 547 | a single argument to double its value. 548 | 549 | Finally, the code calls double with 5 as its argument, which results in 10 being 550 | logged to the console. 551 | 552 | This code demonstrates the concept of currying in JavaScript, where a function 553 | returns another function that can be partially applied with some arguments. 554 | 555 |
556 |574 | 575 | #### Answer: A 576 | 577 | The correct answer is A. 578 | 579 | In JavaScript, an iterable is an object that defines a sequence and can be 580 | iterated over using a loop. 581 | 582 | An iterator is an object that knows how to access the elements of an iterable 583 | one at a time. 584 | 585 | An iterable object has a method with the key `Symbol.iterator`, which returns an 586 | iterator object. 587 | 588 | The iterator object has a `next()` method, which returns an object with two 589 | properties: `value`, which is the next element in the sequence, and `done`, 590 | which is a boolean indicating whether the iterator has reached the end of the 591 | sequence. 592 | 593 | Iterables are commonly used in many real-time applications while working with 594 | large datasets, or while implementing custom data structures 595 | 596 |
597 |627 | 628 | #### Answer: D 629 | 630 | The correct answer is D. 631 | 632 | The `counter` function is a generator function that creates an infinite loop 633 | that yields incrementing values of `i`. 634 | 635 | The `gen` variable is set to the generator function, and each call to 636 | `gen.next()` returns an object with the value property set to the next yielded 637 | value. 638 | 639 | The `console.log` statements then print the values returned by `gen.next()`. 640 | 641 | A generator function is a special type of function that can be used to control 642 | the iteration over a sequence of values. 643 | 644 | Unlike traditional functions, generator functions allow you to pause and resume 645 | their execution, and yield multiple values over time. 646 | 647 |
648 |664 | 665 | #### Answer: B 666 | 667 | Circular references occur when two or more objects reference each other, 668 | creating a loop that prevents the objects from being garbage collected. 669 | 670 | This can cause a memory leak if the objects are no longer needed but cannot be 671 | freed because of the circular reference. 672 | 673 | Options A, C, and D do not typically cause memory leaks in JavaScript. 674 | 675 | Garbage collection is the process of automatically freeing up memory that is no 676 | longer being used by a program. 677 | 678 | In JavaScript, the mark and sweep algorithm is commonly used for garbage 679 | collection. 680 | 681 | This algorithm works by first marking all objects in memory that are still being 682 | referenced by the program, then sweeping through and freeing up any memory that 683 | is not marked as in use. 684 | 685 |
686 |732 | 733 | #### Answer: C 734 | 735 | When the code is executed, the main() function is called, which is an async 736 | function that uses await to get data from the `getData()` function. 737 | 738 | Once the data is retrieved, the `console.log(data)` statement logs "Data 739 | retrieved successfully" to the console. 740 | 741 | After that, the `throw new Error("Something went wrong")` statement throws an 742 | error. 743 | 744 | The `catch` block catches the error and logs 745 | `"Caught an error: Something went wrong"` to the console, and then returns the 746 | string `"Error occurred"`. 747 | 748 | Finally, the finally block is executed and logs `"Finally block executed."` to 749 | the console, and then returns the string `"Finally block value"`. 750 | 751 | When the `main()` function is called, it returns a promise because it is an 752 | async function. Since the `finally` block also returns a value, that value will 753 | be the final resolved value of the promise. 754 | 755 | Therefore, when `console.log(main())` is called, `"Finally block executed."` and 756 | `"Finally block value"` will be logged to the console. 757 | 758 | Try, catch, and finally are keywords used in JavaScript to handle runtime 759 | errors. 760 | 761 |
762 |795 | 796 | #### Answer: B 797 | 798 | Because `break` statement is not valid inside the callback function passed to 799 | `forEach`. 800 | 801 | `forEach` does not support early termination using the `break` statement. 802 | Therefore, an error is thrown: 803 | `"Uncaught SyntaxError: Illegal break statement".` 804 | 805 | In case of for of loop, `break` statement is allowed. 806 | 807 | To fix the issue, remove the `break` statement from forEach and it should work. 808 | 809 | In general, `for of` is recommended over `for in` or `forEach` 810 | 811 |
812 |833 | 834 | #### Answer: A 835 | 836 | The `array.push()` method in JavaScript adds one or more elements to the end of 837 | an array and returns the new length of the array. 838 | 839 | In the given code, `arr` is an array with the values `[1, 2, 3, 4]`. The 840 | `push()` method is called with the argument 5, which adds `5` to the end of the 841 | `arr` array. 842 | 843 | The `push()` method returns the new length of the array after the addition of 844 | the element(s). In this case, the new length of arr will be 5 because `5` is 845 | added to the end of the array. 846 | 847 |
848 |869 | 870 | #### Answer: B 871 | 872 | The `array.unshift()` method in JavaScript adds one or more elements to the 873 | beginning of an array and returns the new length of the array. 874 | 875 | In the given code, `arr` is an array with the values `[3, 5, 7, 9]`. The 876 | `unshift()` method is called with the arguments 1 and 2, which adds 1 and 2 to 877 | the beginning of the `arr` array. 878 | 879 | The `unshift()` method returns the new length of the array after the addition of 880 | the element(s). In this case, the new length of `arr` will be 6 because 1 and 2 881 | are added to the beginning of the array, shifting the existing elements to the 882 | right. 883 | 884 |
885 |906 | 907 | #### Answer: B 908 | 909 | The `Array.pop()` method in JavaScript removes the last element from an array 910 | and returns that element. 911 | 912 | In this case, `myArray` is an array with elements `[1, 2, 3, 4, 5]`, and 913 | `myArray.pop()` is called, which removes the element 5 from the array and 914 | returns it. 915 | 916 |
917 |938 | 939 | #### Answer: A 940 | 941 | The `Array.shift()` method removes the first element from the `arr` array, which 942 | is `10`, and returns it. The resulting `arr` array will then be 943 | `[20, 30, 40, 50]`. 944 | 945 | So, option A is the correct answer as it reflects the correct value of 946 | `removedElement` and the updated state of `arr` after `Array.shift()` is called. 947 | Option B is incorrect as it states that `removedElement` will be 50, which is 948 | not true. Option C is also incorrect as it state that `arr` remains unchanged, 949 | which is not accurate. Option D is slightly confusing as it states that 950 | `Array.shift()` returns the array, which is not true. 951 | 952 |
953 |974 | 975 | #### Answer: B 976 | 977 | The `Array.splice()` method is used to modify an array by adding, removing, or 978 | replacing elements. 979 | 980 | In this case, the code snippet uses `arr.splice(1, 2, 'a', 'b')`, which starts 981 | from index 1 (removing 2 elements) and inserts the elements `a` and `b` in their 982 | place. The elements that are removed (i.e., 2 and 3) are returned and assigned 983 | to the variable removed. After execution, removed will be `[2, 3]` and `arr` 984 | will be `[1, 'a', 'b', 4, 5]`. Option C is incorrect as it includes the inserted 985 | elements in the removed array, which is not accurate. Option D is also incorrect 986 | as it mentions the incorrect elements that are removed from the array. 987 | 988 |
989 |1012 | 1013 | #### Answer: A 1014 | 1015 | The `Array.indexOf()` method searches for the index of the first occurrence of 1016 | the specified value in the array fruits. In this case, "orange" is found at 1017 | index 2, so `index` will be 2. 1018 | 1019 | The `Array.lastIndexOf()` method searches for the index of the last occurrence 1020 | of the specified value in the array fruits. In this case, "apple" appears twice 1021 | in the array and its last occurrence is at index 4, so `lastIndex` will be 4. 1022 | 1023 | On the other hand, the `Array.includes()` method checks if the specified value 1024 | "grape" exists in the array fruits, and since "grape" is present in the array, 1025 | `result` will be true. 1026 | 1027 |
1028 |1063 | 1064 | #### Answer: D 1065 | 1066 | The `Array.filter()` method returns an array containing all elements for which 1067 | the function passed to it returns true. In this case, the function 1068 | `isDivisibleBy7` returns true for any number that is divisible by 7. In the 1069 | `nums` array, 7 and 28 are divisible by 7, so `nums.filter(isDivisibleBy7)` 1070 | returns [28, 7]. 1071 | 1072 | The `Array.find()` method returns the first element in the array for which the 1073 | function passed to it returns true. In this case, the function passed to it 1074 | returns true for any number less than 10. There are multiple numbers in `nums` 1075 | that are less than 10, but since `Array.find()` only returns the first for which 1076 | it is true, `nums.find((num) => num < 10)` returns 7. 1077 | 1078 | The `Array.findIndex()` method is similar to the `Array.find()` method, but 1079 | returns the index of the first element in the array for which the function 1080 | passed to it returns true, rather than the element itself. In this case, the 1081 | function passed to it returns true for 28, since the 28 / 2 == 14. 28 is in the 1082 | array `nums` and is at index 0, so `nums.find((num) => num / 2 == 14)` 1083 | returns 0. 1084 | 1085 |
1086 |1107 | 1108 | #### Answer: B 1109 | 1110 | The `Array.map()` method in JavaScript creates a new array by applying a 1111 | provided function to each element of the original array. 1112 | 1113 | In this case, the provided function `num => num * 2` multiplies each number in 1114 | the numbers array by 2, resulting in a new array `[2, 4, 6, 8, 10]`. 1115 | 1116 |
1117 |1138 | 1139 | #### Answer: B 1140 | 1141 | `Array.reduce()` takes an array and "reduces" it to a single value by repeatedly 1142 | applying a function to each element and keeping track of the accumulated result. 1143 | It's commonly used for tasks such as summing up an array of numbers, finding the 1144 | maximum value, or concatenating an array of strings into a single string. 1145 | 1146 | In this case, the reduce() method takes a callback function that is executed for 1147 | each element of the array. The callback function takes two parameters, `acc` and 1148 | `val`, which represent the accumulator and the current value of the array, 1149 | respectively. 1150 | 1151 | Inside the callback function, the current value of the array is added to the 1152 | accumulator and the result is returned. The `reduce()` method updates the value 1153 | of the accumulator with each iteration until it has iterated over all the 1154 | elements of the array. 1155 | 1156 | Finally, the `reduce()` method returns the final value of the accumulator, which 1157 | is the sum of all the numbers in the array, that is 15. 1158 | 1159 |
1160 |1181 | 1182 | #### Answer: A 1183 | 1184 | The `reduceRight()` method is similar to the `reduce()` method, except that it 1185 | starts reducing the array from the rightmost element to the leftmost element. 1186 | The `reduceRight()` method applies a function against an accumulator and each 1187 | value of the array (from right-to-left) to reduce it to a single value. 1188 | 1189 | In the given code snippet, the `arr` array contains the values `[1, 2, 3, 4]`. 1190 | The `reduceRight()` method is called on this array with a callback function that 1191 | adds the accumulator `acc` with the current element `curr`. 1192 | 1193 | In the first iteration, the `curr` value will be `4`, and the acc value will be 1194 | `undefined`, since no initial value is provided. Therefore, the result of the 1195 | first iteration will be `4`. 1196 | 1197 | In the second iteration, the `curr` value will be `3`, and the `acc` value will 1198 | be the result of the previous iteration, which is `4`. Therefore, the result of 1199 | the second iteration will be `7`. 1200 | 1201 | In the third iteration, the `curr` value will be `2`, and the `acc` value will 1202 | be the result of the previous iteration, which is `7`. Therefore, the result of 1203 | the third iteration will be `9`. 1204 | 1205 | In the fourth and final iteration, the `curr` value will be `1`, and the `acc` 1206 | value will be the result of the previous iteration, which is `9`. Therefore, the 1207 | result of the fourth iteration will be `10`. 1208 | 1209 | Therefore, the final output of the code will be `10`. Hence, the correct option 1210 | is A. 1211 | 1212 |
1213 |1234 | 1235 | #### Answer: D 1236 | 1237 | By default the `sort()` method sorts elements by character so 11235 comes before 1238 | 3.14159 because 1 comes before 3. 1239 | 1240 | Words and letters are sorted alphabetically by ASCII code so "Centauri" which 1241 | starts with an uppercase C (ASCII code 67) sorts before "canine" which starts 1242 | with a lowercase c (ASCII code 99). 1243 | 1244 | Undefined elements always sort to the end of an array. 1245 | 1246 | Thus, the final output of the code will be [ 11235, 3.14159, 'Centauri', 1247 | 'canine', undefined ] which is option D. 1248 | 1249 |
1250 |1273 | 1274 | #### Answer: B 1275 | 1276 | With Array Destructuring it is possible to unpack certain values from an array 1277 | into individual variables. The values we created in the left hand side 1278 | (`a, b, c, rest`) correspond to the values and the order of the array we 1279 | assigned in the right hand side (`numbers`). 1280 | 1281 | - The variable `a` corresponds to the first element of the array, which is `1`. 1282 | 1283 | - Since we did not specify a variable for the next value `2`, the value is not 1284 | taken into account in the evaluation and is skipped. 1285 | 1286 | - The variable `b` corresponds to the third element of the array, which is `3`. 1287 | 1288 | - It is possible to set default values for the variables if the element in the 1289 | array is `undefined`. Since the fourth element in the array is `undefined`, 1290 | the variable `c` has the default value `2`. 1291 | 1292 | - With the spread operator (`...`) we can assign the remaining values of the 1293 | array to a variable. Since the values `[ 6, 7, 8, 9 ]` are the remaining 1294 | values of the array, they are assigned to the variable `rest`. 1295 | 1296 | Therefore, the final result is: `1 3 2 [ 6, 7, 8, 9 ]`, which is option B. 1297 | 1298 |
1299 |1321 | 1322 | #### Answer: B 1323 | 1324 | `new Date()` will return the current date and time followed by the two specified 1325 | dates in the format "YYYY-MM-DDTHH:MM:SS.sssZ", where "Z" represents the UTC 1326 | time zone offset. 1327 | 1328 | `YYYY-MM-DDTHH:mm:ss.sssZ` is a format used to represent dates and times in the 1329 | ISO 8601 standard. It consists of the following components: 1330 | 1331 | - `YYYY`: Four-digit year (0000 to 9999), or as an expanded year with + or - 1332 | followed by six digits. The sign is required for expanded years. -000000 is 1333 | explicitly disallowed as a valid year. 1334 | - `MM`: Two-digit month (01 = January, 02 = February, and so on). It defaults 1335 | to 01. 1336 | - `DD`: Two-digit day of the month (01 to 31) 1337 | - `T`: A separator indicating the start of the time component 1338 | - `HH`: Two-digit hour of the day in 24-hour format (00 to 23). As a special 1339 | case, 24:00:00 is allowed, and is interpreted as midnight at the beginning of 1340 | the next day. Defaults to 00. 1341 | - `mm`: Two-digit minute of the hour (00 to 59). Defaults to 00. 1342 | - `ss`: Two-digit second of the minute (00 to 59). Defaults to 00. 1343 | - `.sss`: Millisecond component (000 to 999). Defaults to 000. 1344 | - `Z`: A suffix indicating that the time is in UTC (Coordinated Universal Time), 1345 | with no offset. It can either be the literal character Z (indicating UTC), 1346 | or + or - followed by HH:mm, the offset in hours and minutes from UTC. 1347 | 1348 |
1349 |1378 | 1379 | #### Answer: A 1380 | 1381 | The provided code creates a Date object initialized with the date and time of 1382 | "March 15, 1975 23:15:30". 1383 | 1384 | Then, it modifies the minutes and UTC date of the date object using the 1385 | `setMinutes()` and `setUTCDate()` methods, respectively. 1386 | 1387 | Finally, it logs the updated values of minutes, year, and UTC date using 1388 | `console.log()`. 1389 | 1390 | After modifying the minutes to 10 using `setMinutes(10)`, the `getMinutes()` 1391 | method returns the updated value of 10. 1392 | 1393 | After modifying the UTC date to 5 using `setUTCDate(5)`, the `getUTCDate()` 1394 | method returns the updated value of 5. 1395 | 1396 | The `getFullYear()` method returns the unchanged year, which is 1975. 1397 | 1398 |
1399 |1422 | 1423 | #### ANSWER: B 1424 | 1425 | The code calculates the difference in days between the date "2023-5-1" and the 1426 | next US election date "2024-11-5". It uses the `Date` object to create two 1427 | dates: `date1` represents May 1, 2023, and `next_us_election` represents 1428 | November 5, 2024. 1429 | 1430 | The `getTime()` method is used to get the time value in milliseconds for each 1431 | date. By subtracting the time value of `date1` from `next_us_election`, we get 1432 | the time difference in milliseconds. 1433 | 1434 | To convert the time difference from milliseconds to days, we divide it by the 1435 | number of milliseconds in a day (1000 _ 3600 _ 24). The result is stored in the 1436 | variable `difference_in_days`. 1437 | 1438 | Finally, the `parseInt()` function is used to convert the difference_in_days 1439 | value to an integer, and the result is logged to the console along with the 1440 | "Days" string. The output will be "554 Days". 1441 | 1442 |
1443 |1479 | 1480 | #### ANSWER: A 1481 | 1482 | The code defines an object literal `person` with properties such as `name`, 1483 | `age`, `hobbies`, and `address`, and a method `sayHello`. 1484 | 1485 | The `console.log()` statements print the value of `name`, the second element of 1486 | the `hobbies` array (which is "traveling"), and the value of the `city` property 1487 | in the `address` object (which is "New York"). 1488 | 1489 | Finally, the method `sayHello` is called on the `person` object using dot 1490 | notation, which outputs the string "Hello, my name is John" to the console. 1491 | 1492 |
1493 |1526 | 1527 | #### Answer: B 1528 | 1529 | The code defines a constructor function `User` that creates `user` objects with 1530 | a `username` property and an `updateUsername` method. Two `user` objects, 1531 | `user1` and `user2`, are created with initial usernames 'kirandash' and 1532 | 'bgwebagency' respectively. 1533 | 1534 | The `updateUsername` method is called on both `user1` and `user2` objects to 1535 | update their usernames. `user1`'s username is updated to 'kirandash-website', 1536 | and `user2`'s username is updated to 'bgwebagency-app'. 1537 | 1538 | Finally, the code logs the concatenation of `user1.username` and 1539 | `user2.username`, which results in the output 'kirandash-website 1540 | bgwebagency-app'. 1541 | 1542 |
1543 |1576 | 1577 | #### ANSWER: B 1578 | 1579 | The `call` function is used to invoke the `greet` function with the `person` 1580 | object as the context (the value of `this`) and `'John'` as the argument. 1581 | 1582 | The `apply` function is used to invoke the `greet` function with the `person` 1583 | object as the context (the value of `this`) and an array ['Alex'] as the 1584 | arguments. 1585 | 1586 | The `bind` function is used to create a new function `greetPerson` with the 1587 | `person` object as the bound context (the value of `this`). 1588 | 1589 | In summary, the code demonstrates how `call`, `apply`, and `bind` can be used to 1590 | invoke a function with a specific context and arguments 1591 | 1592 |
1593 |1629 | 1630 | #### Answer: A 1631 | 1632 | The static method `makeSound()` is defined on the `Animal` class, and is 1633 | accessible directly through the class itself, i.e., `Animal.makeSound()`. This 1634 | will output `"Generic animal sound"` to the console. 1635 | 1636 | However, when we try to call `makeSound()` on an instance of the Animal class 1637 | `(a1.makeSound() and a2.makeSound())`, we get a TypeError, because static 1638 | methods can only be accessed through the class itself and not through its 1639 | instances. 1640 | 1641 |
1642 |1697 | 1698 | #### Answer: A 1699 | 1700 | Explanation: In this example, we have a base class called `Animal` that defines a constructor and an `eat()` method. The subclass `Dog` extends the `Animal` class and adds its own constructor, `bark()` method, and a specific property `breed`. 1701 | 1702 | Furthermore, we extend the built-in `Array` class using the `class` syntax to 1703 | create a `CustomArray` class. The `CustomArray` class adds a custom method 1704 | called `sum()` that calculates the sum of the array elements. 1705 | 1706 | In the usage section, we create an instance of `Dog` named `dog` with the name 1707 | "Buddy" . We can call the inherited `eat()` method from the `Animal` class, the 1708 | `bark()` method defined in the `Dog` class. 1709 | 1710 | Additionally, we create an instance of `CustomArray` called `numbers` and add 1711 | some numbers to it. We can call the custom `sum()` method, which is added to the 1712 | built-in `Array` class through subclassing. 1713 | 1714 | This example showcases inheritance, subclassing, and extending a built-in class 1715 | in JavaScript, illustrating how classes can be extended and customized to add 1716 | additional functionality. 1717 | 1718 |
1719 |1748 | 1749 | #### Answer: A 1750 | 1751 | In the code above, we have an object literal called `person` with properties `name`, `age`, and `city`. We then use object destructuring to extract those properties into separate variables (`name`, `age`, and `city`). After destructuring, we can use these variables to access the corresponding values from the object. 1752 | 1753 |
1754 |1793 | 1794 | #### Answer: B 1795 | 1796 | The `module.js` file exports three entities: 1797 | 1798 | 1. `PI` is a named export, exported using the `export` keyword. 1799 | 2. `calculateArea` is a named export, exported using the `export` keyword. 1800 | 3. `calculateCircumference` is the default export, exported using the 1801 | `export default` syntax. 1802 | 1803 | In the `main.js` file, we import `PI` and `calculateArea` as named exports using 1804 | the destructuring assignment syntax. We also import `calculateCircumference` as 1805 | the default export. The import statements reference the `module.js` file using 1806 | the relative file path `./module.js`. 1807 | 1808 | The outputs of the `console.log` statements will be: 1809 | 1810 | - `console.log(PI)` will output `3.14159` since we imported the named export 1811 | `PI`. 1812 | - `console.log(calculateArea(5))` will output `78.53975` since we imported the 1813 | named export `calculateArea` and called the function with a radius of 5. 1814 | - `console.log(calculateCircumference(5))` will output `62.8318` since we 1815 | imported the default export `calculateCircumference` and called the function 1816 | with a radius of 5. 1817 |
1818 |1846 | 1847 | #### Answer: C 1848 | 1849 | Named exports are imported into different files with braces and must be imported 1850 | with the name of the object, function or variable that was exported. In this 1851 | example, a function with the name `foo` is exported from the file `foo.js`. 1852 | Accordingly, the correct expression is: `import { foo } from "./foo"`. 1853 | 1854 |
1855 |1871 | 1872 | #### Answer: D: Both option B and C. 1873 | 1874 | Explanation: Both option B and C are valid syntaxes for importing a default export from a module and assigning it an alias. The difference between the two syntaxes is that option B does not use the { default as myAlias } syntax. This means that the default export will be imported under the name myAlias, rather than the name default. 1875 | 1876 | Here is an example of how to use the option B syntax:{import myAlias from 'module';},This will import the default export from the module module and assign it the name myAlias. You can then use the myAlias variable to access the default export from the module module. 1877 | Here is an example of how to use the option C syntax:{import { default as myAlias } from 'module';},This will import the default export from the module module and assign it the alias myAlias. You can then use the myAlias alias to access the default export from the module module. 1878 | 1879 | The choice of which syntax to use is up to you. The option B syntax is simpler, 1880 | but it can lead to collisions if there is already a variable named myAlias in 1881 | the current scope. The option C syntax is more verbose, but it avoids 1882 | collisions. 1883 | 1884 |
1885 |1902 | 1903 | #### Answer: B `JSON.stringify()` with a custom replacer function. 1904 | 1905 | Explanation: The `JSON.stringify()` method can be used to convert a JavaScript 1906 | object to a `JSON` string. However, by default, it will not preserve data types 1907 | like `Dates` and `RegEx`. To preserve these data types, you can use a custom 1908 | replacer function. The replacer function takes an object as input and returns a 1909 | new object with the modified values. 1910 | 1911 | The code below would show you how to use a custom replacer function to preserve 1912 | data types: 1913 | 1914 |
1915 | 1916 | ```js 1917 | function replacer(key, value) { 1918 | if (typeof value === 'Date') { 1919 | return value.toJSON() 1920 | } else if (typeof value === 'RegExp') { 1921 | return value.toString() 1922 | } else { 1923 | return value 1924 | } 1925 | } 1926 | 1927 | const object = { 1928 | date: new Date(), 1929 | regex: /some regex/, 1930 | } 1931 | 1932 | const jsonString = JSON.stringify(object, replacer) 1933 | ``` 1934 | 1935 |