JavaScript Functions Flashcards
How do you add an event listener to the window
window.addEventListener(event, callback);
What are tricky about the ‘blur’ and ‘focus’ and ‘resize’ events when adding to a window?
You have to use the actual event on the window object:
window. onblur
window. onfocus
window. resize
What does ‘reduce’ do?
It operates on an array, and takes a callback that allows you to sum ( or do whatever ) to the elements in the array.
Array.prototype.reduce(callback, initialvalue)
Callback(previous, current, index, array).
myarray.reduce(function (a, b) { return a + b; })
What function makes an element (canvas, video etc) fullscreen?
requestFullScreen (but it’s new, so it uses extensions)
webkitRequestFullScreen();
The only gotcha - you must call it from a user action. I.e. A user must press a button or something.
What function do you use to get the rectangle that bounds an object (useful for determining mouse position in games)?
getBoundingClientRect();
NOTE: It gives you back an object that has ‘top’, ‘left’ etc. Not x and y!!!
What object is used for ajax requests?
var xobj = XMLHttpRequest();
What function on an XMLHttpRequest object do you use to specify that you want json?
xobj.overrideMimeType(‘application/json’);
What function do you use to make a get request for a json file?
xobj.open(‘GET’, ‘myfile.json’, true);
What function is used to prevent the usual action of an event from occurring (so you can intercept and do something else)?
e.preventDefault();
What does Math.max do?
Math.max(10, 20); // Returns 20
Returns the largest of two or more numbers
Just be aware -
Math.max(-20, -10) will return -10. This is correct, just a tricky one to spot.
NOTE: There is also Math.min
Is this valid?
[1, 2, 3, 4].reduce(function(a, b) { return a + b; }
Yup - because reduce is a member of Array.prototype, it will work being called directly on an array like this.
What is the code equivaleent way to get the media query values @media (width) @media(height)
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0) var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
What function will give you the inside height / width of a window?
There isn’t one - use window.innerHeight .innerWidth
OR right your own function that returns those values (not on e a browser, that gives the value inside the scrollbars)
How would you copy an array, in the simplist, quickest method?
return array.slice();
return array.slice();
throw “Error”
You can of course throw objects as well. If you create a new exception object.
throw new UserException();