JavaScript Basics Flashcards
What is JS comment syntax?
// for inline, /* */ for multiline
How do we declare a function as a variable?
var addTwoNumbers = function(a, b) { return a + b; };
How do we declare a function?
function addTwoNumbers(a, b) { return a + b; }
What does a variable declared without the ‘var’ keyword become?
Global in scope.
What are the JS primitives (i.e. only things which aren’t objects)?
strings, booleans, numbers, ‘undefined’, and ‘null’
What is object literal syntax?
var person = {
firstName : ‘Boaz’,
lastName : ‘Sender’
};
When using bracket notation with an object to retrieve the value of a key, what must the key be?
It must be given as a string (with quotes).
What is the syntax to declare an object method?
var person = { firstName : 'Boaz', lastName : 'Sender', greet : function(name) { log( 'Hi, ' + name ); } };
What does ‘this’ refer to?
The object that is the context in which the function was called. Note that this is NOT necessarily the context in which the function was defined.
What is the JS equivalent of Ruby’s send, and how can it be used to remove ambiguity for ‘this’?
‘.call’ can be used to ensure that ‘this’ is in the context of the original object definition:
var person = {
firstName : ‘Boaz’,
lastName : ‘Sender’,
greet : function(greeting, punctuation) {
log( greeting + ‘, ‘ + this.firstName + punctuation );
}
};
var sayIt = person.greet;
sayIt.call( person, ‘Hello’, ‘!!1!!1’ );
What is JS for loop syntax?
for (var loopVar = initialVal; end_condition; increment/decrement){code block per iteration}
What are the JS falsy values?
undefined, null, NaN, 0, ‘’ (this last one is an empty string)
What will the following code return:
log(‘4’ + 3)
JS is a loosely typed language, meaning mathematical operations with non-number values will NOT throw an error. This means the code will return:
‘43’
How can we call a method on each element of an array?
forEach([1, 2, 3], logIfEven);
How can we pass an anonymous function?
// **Notice the formatting!** [1, 2, 3].forEach(function (num) { if ((num % 2) == 0) { console.log(num); } });