Coding Questions

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

What is the outcome of the two alerts? var foo = "Hello"; (function() { var bar = " World"; alert(foo + bar); })(); alert(foo + bar);

"Hello World" "bar" is not defined

What is the value of window.foo? ( window.foo || (window.foo = "bar" ) );

"bar"

What will the code below output? Explain your answer. console.log(0.1 + 0.2); console.log(0.1 + 0.2 == 0.3);

Numbers in JavaScript are all treated with floating point precision, and as such, may not always yield the expected results. 0.30000000000000004 false

Can you write a function that deeply flattens an array? //example input = [0, 1, [2, 3], [[4, [5]]]]; output = [0, 1, 2, 3, 4, 5];

function flatten(arr) { let newArr = []; let flat = (innerArr) => { return innerArr.map((num) => { return num.length >= 1 ? flat(num) : newArr.push(num); }) } flat(arr); return newArr; }

Write a simple function (less than 80 characters) that returns a boolean indicating whether or not a string is a palindrome.

function palindrome(string) { string = string.toLowerCase(); return string === string.split('').reverse().join(''); }

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note: You must do this in-place without making a copy of the array. Minimize the total number of operations.

function removeZero(arr) { let j = 0; arr.map((num, i) => { if(num !== 0) { let temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; j++; } }); return arr; } removeZero([0, 1, 0, 3, 12]);

We have an array of objects A and an array of indexes B. Reorder objects in array A with given indexes in array B. Do not change array A's length. //example var A = [C, D, E, F, G]; var B = [3, 0, 4, 1, 2]; sort(A, B); // A is now [D, F, G, C, E];

function sortArr(A, B) { let newObj = {}; for (let i = 0; i < A.length; i++) { newObj[B[i]] = A[i]; } for (let j in newObj) { A[j] = newObj[j]; } return A; } sortArr(['C', 'D', 'E', 'F', 'G'], [3, 0, 4, 1, 2]) OR function sort(A, B) { let result = []; B.map((index, i) => { result[index] = A[i]; }) return result; }

Manually calculate the square root of a number with Javascript.

function sqrt(num) { for (let i = 0; i * i < num; i++) { if (i * i === num) { return i; } } }

Write a sum method which will work properly when invoked using either syntax below. console.log(sum(2,3)); // Outputs 5 console.log(sum(2)(3)); // Outputs 5

function sum(x, y) { if (y !== undefined) { return x + y; } else { return function(y) { return x + y; }; } } When a function is invoked, JavaScript does not require the number of arguments to match the number of arguments in the function definition. If the number of arguments passed exceeds the number of arguments in the function definition, the excess arguments will simply be ignored. On the other hand, if the number of arguments passed is less than the number of arguments in the function definition, the missing arguments will have a value of undefined when referenced within the function. So, in the above example, by simply checking if the 2nd argument is undefined, we can determine which way the function was invoked and proceed accordingly.

What will be the output when the following code is executed? Explain. console.log(false == '0') console.log(false === '0')

true false

What is the value of foo.x? var foo = {n: 1}; var bar = foo; foo.x = foo = {n: 2};

{n: 2}

What would the following lines of code output to the console? console.log("0 || 1 = "+(0 || 1)); console.log("1 || 2 = "+(1 || 2)); console.log("0 && 1 = "+(0 && 1)); console.log("1 && 2 = "+(1 && 2));

0 || 1 = 1 1 || 2 = 1 0 && 1 = 0 1 && 2 = 2 The or (||) operator. In an expression of the form X||Y, X is first evaluated and interpreted as a boolean value. If this boolean value is true, then true (1) is returned and Y is not evaluated, since the "or" condition has already been satisfied. If this boolean value is "false", though, we still don't know if X||Y is true or false until we evaluate Y, and interpret it as a boolean value as well. Accordingly, 0 || 1 evaluates to true (1), as does 1 || 2. The and (&&) operator. In an expression of the form X&&Y, X is first evaluated and interpreted as a boolean value. If this boolean value is false, then false (0) is returned and Y is not evaluated, since the "and" condition has already failed. If this boolean value is "true", though, we still don't know if X&&Y is true or false until we evaluate Y, and interpret it as a boolean value as well. However, the interesting thing with the && operator is that when an expression is evaluated as "true", then the expression itself is returned. This is fine, since it counts as "true" in logical expressions, but also can be used to return that value when you care to do so. This explains why, somewhat surprisingly, 1 && 2 returns 2 (whereas you might it expect it to return true or 1).

In what order will the numbers 1-4 be logged to the console when the code below is executed? Why? (function() { console.log(1); setTimeout(function(){console.log(2)}, 1000); setTimeout(function(){console.log(3)}, 0); console.log(4); })();

1, 4, 3, 2 1 and 4 are displayed first since they are logged by simple calls to console.log() without any delay. 2 is displayed after 3 because 2 is being logged after a delay of 1000 msecs (i.e., 1 second) whereas 3 is being logged after a delay of 0 msecs. When a value of zero is passed as the second argument to setTimeout(), it attempts to execute the specified function "as soon as possible". Specifically, execution of the function is placed on the event queue to occur on the next timer tick. Note, though, that this is not immediate; the function is not executed until the next tick. That's why in the above example, the call to console.log(4) occurs before the call to console.log(3) (since the call to console.log(3) is invoked via setTimeout, so it is slightly delayed).

What will the following code output to the console: console.log((function f(n){return ((n > 1) ? n * f(n-1) : n)})(10));

10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 10! = 3628800

What is the value of foo? var foo = 10 + '20';

1020

What is the value of foo.length? var foo = []; foo.push(1); foo.push(2);

2

What will be the output of the following code: for (var i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, i * 1000 ); }

The code sample shown will not display the values 0, 1, 2, 3, and 4 as might be expected; rather, it will display 5, 5, 5, 5, and 5. The reason for this is that each function executed within the loop will be executed after the entire loop has completed and all will therefore reference the last value stored in i, which was 5. Closures can be used to prevent this problem by creating a unique scope for each iteration, storing each unique value of the variable within its scope, as follows: for (var i = 0; i < 5; i++) { (function(x) { setTimeout(function() { console.log(x); }, x * 1000 ); })(i); } This will produce the presumably desired result of logging 0, 1, 2, 3, and 4 to the console.

var a={}, b={key:'b'}, c={key:'c'}; a[b]=123; a[c]=456; console.log(a[b]);

The output of this code will be 456 (not 123). The reason for this is as follows: When setting an object property, JavaScript will implicitly stringify the parameter value. In this case, since b and c are both objects, they will both be converted to "[object Object]". As a result, a[b] and a[c] are both equivalent to a["[object Object]"] and can be used interchangeably. Therefore, setting or referencing a[c] is precisely the same as setting or referencing a[b].

Consider the code snippet below. What will the console output be and why? (function(x) { return (function(y) { console.log(x); })(2) })(1);

The output will be 1, even though the value of x is never set in the inner function. A closure is a function, along with all variables or functions that were in-scope at the time that the closure was created. In JavaScript, a closure is implemented as an "inner function"; i.e., a function defined within the body of another function. An important feature of closures is that an inner function still has access to the outer function's variables. Therefore, in this example, since x is not defined in the inner function, the scope of the outer function is searched for a defined variable x, which is found to have a value of 1.

Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example : Input : [1 2 2 3 1] Output : 3

^= is an XOR (exclusive or) bitwise operator module.exports = { //param A : array of integers //return an integer singleNumber : function(A){ var a; A.forEach(function(item){ a ^= item; }); return a; } };

What will the code below output to the console and why? var arr1 = "john".split(''); var arr2 = arr1.reverse(); var arr3 = "jones".split(''); arr2.push(arr3); console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1)); console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));

arr1 = ['j', 'o', 'h', 'n'] arr2 = ['n', 'h', 'o', 'j'] arr3 = ['j', 'o', 'n', 'e', 's'] arr2.push(arr3) = ['n', 'h', 'o', 'j',[ 'j', 'o', 'n', 'e', 's']] arr2 = arr1 since it's called on arr1.reverse() array 1: length=5 last=['j', 'o', 'n', 'e', 's'] array 2: length=5 last=['j', 'o', 'n', 'e', 's']

How would you make this work? add(2, 5); // 7 add(2)(5); // 7

function add(num1, num2) { return num1 + num2; } var add = function(x) { return function(y) { return x + y; }; }

Given a string String="ABCSC" Check whether it contains a Substring="ABC"? If no , return "-1". If yes , remove the substring from string and return "SC".

function checkString(string) { return ((string.indexOf("ABC") != -1) ? (string.replace(/ABC/gm,"")) : (-1)); } checkString("ABCSC");


Kaugnay na mga set ng pag-aaral

Chapter 6 - THE NATURE OF WORK MOTIVATION

View Set

Arab-Israeli Conflict Final Exam

View Set

Object Oriented Programming (OOP)

View Set

Final Exam: Chapters 18-21 (ART 1030 Austin Peay State University)

View Set

Cognitive Exam 2 - quiz questions

View Set

BIO311C Exam 3 (Biochemistry) Review

View Set

VETT 117 Unit 6 Review & Quiz Questions

View Set