javascript

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

What is the difference between == and ===?

=== strictly equal so 0 == false // true 0 === false // false, because they are of a different type 1 == "1" // true, automatic type conversion for value only 1 === "1" // false, because they are of a different type null == undefined // true null === undefined // false '0' == false // true '0' === false // false

Explain how JSONP works (and how it's not really AJAX).

An ajax call is an actual HTTP request from your client directly to a server In a JSONP call, the client creates a script tag and puts a URL on it with an callback=xxxx query parameter on it.

Explain AJAX in as much detail as possible.

Asynchronous JavaScript and XML. its a way to communicate to the server without reloading the page when we receive the data from the server we can manipulate it and display it It uses a host object called XMLHttpRequest to communicate to a server-side script to retrieve data formatted in either JSON, XML, HTML, or plain text.

difference between call and apply

Call and apply are pretty interchangeable. Just decide whether it's easier to send in an array or a comma separated list of arguments. I always remember which one is which by remembering that Call is for comma (separated list) and Apply is for Array

what are AJAX apps?

apps that pull new content without a page reload Asynchronous JavaScript and XML to retrieve new content for a page like new articles or infinite scroll site or to notify you of new emails we use a tool called XML HTTP Request (XHR) (also known as ajax apps)

what is closure?

are created whenever a variable that is define outside of the current scope is accessed from w/i some inner scope

get total number of arguments passed

arguments.length

how to create a cookie?

assign a string value to the document cookie object document.cookie = "key1 = value1; key2= value2;"

(function() { var a = b = 3; }) this really means ?

b=3 var a =b typof a is undefined b is defined since b ends up being a global variable since it is not precedded by the var keyword

Explain Function.prototype.bind.

bind allows you to set which object is treated as this within the function call.

how do we get an element from the dom

byId getElementsByTagName ByClassName we can also manipulate by css selector using document.querySelector var pageHeader = document.querySelector('#header'); var buttons = document.querySelectorAll(.btn);

foreach()

calls a function for each elemnt in the array

how many typed of functions JS supports

can be either named or anonymous

disadvantage of using JS

cant treat it as a full language since it lack important features like cant read or write to files cant be used for networking applications no multithreading or multiprocessing features

return a character at a specific index

charAt()

Why is it called a Ternary expression, what does the word "Ternary" indicate?

comes from the n-ary word setup So a ternary operand accepts three parameters. conditional ? truethy_block : falsey_block

which method comibined the text of two strings and returns a new string

concat()

getting object properties

irena.name

what is a callback?

is a plain JS function that is passed as an argument or option some are just events that are called to give the user a chance to react with a certain state is triggered

difference between undefined and not defined? how to check for this?

not defined for a variable that has not been declared undefined when you use typeof undeclared variable ex) var x; console.log(x); //undefined if (null === yourvar) // Without casting to check if null to check if a variable exisits if (typeof yourvar != 'undefined') // Any scope //if you know the variable existis but dont know if a value is stored in it if (undefined != yourvar)

what is javascript?

programming language with OO capabilities that allows you to interact with HTML pages

What's the difference between an "attribute" and a "property"?

property is for js object and attribute is for html tag properties: JS DOM have properties and are kind of like instance variables like prop or style attribute: are in the html itself rather than in the the DOM

prototypal inheritance works

proptype is an internal objects from which other objects inherit properties a proptype object will inherit all instance which refer to it

how to redirect a url using JS

<head> <script type="text/javascript"> <!-- window.location="http://www.newlocation.com"; //--> </script> </head>

What are HTTP actions? List all HTTP actions that you know, and explain them.

HTTP is basically the set of rules for transferring files and images on the web. POST A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms GET used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data PUT Replaces all current representations of the target resource with the uploaded content

Explain "hoisting".

Hoisting is the JavaScript interpreter's action of moving all variable and function declarations to the top of the current scope. so if you have var foo = "cat"; alert(foo + bar); var bar = "dog" you wont get an error instead it will print cat undefined but if you take our var bar you'll get a reference error

What are the pros and cons of using Promises instead of callbacks?

In short promises are perfect when you deal with multiple async calls in parallel. the main advantage of a callback is locality. the work is preformed in one place so when we have no actual data being handed back a callback is the only appropriate way to handle such an API

Explain what a single page app is and how to make one SEO-friendly.

It's a web application that fits on a single page of a website, single document. more fluid user experience like that of a desktop app since no page reloads. Problems: Indexing and linkability challenges. Fallbacks - HTML pages that display if JS not parsed, for url fragments. Hold the same content the App would show as well as normal indexable links. (lots of work and time) pushState - HTML5 ability to panipulate URL as well as broswer history. Sharable and bookmarkable URL now.

what is JSON

JavaScript Object Notation JSON is used to transfer information - between your browser to a server, or saved in text files for retrieval later is a set of text formatting rules for storing and transferring data in a human readable way its not officialy JS

explain event delegation in react

React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping.

What is the extent of your experience with Promises and/or their polyfills?

Similar to event listeners. Imagine event listener added to object after it happened, can check for success but not failure. Promises - can only succeed or fail once - if promise has succeeded or failed and you later add a callback, correct one will be called. var url = getDefinedParam('upapiBaseUrl', '') + 'email?email=' + search_string; fetch(url) .then(function (response) { return response.json(); }) .then(this.handleEmailSearchResponse) .catch(this.handleSearchError);

What is "use strict";? what are the advantages and disadvantages to using it?

The purpose of "use strict" is to indicate that the code should be executed in "strict mode". With strict mode, you can not, for example, use undeclared variables. ex) "use strict"; x = 3.14; //will throw error

Why would you use something like the load event? Does this event have disadvantages? Do you know any alternatives, and why would you use those?

When used on window it waits for entire document, including pictures to be loaded before running the code. This is good when you need to manipulate the DOM or images and need them to load first. But if not want to wait for images you can use jQuery $(document).ready() method and it won't wait for images and iframes to finish loading.

what is the precedence of a scoped variable?

a local variable takes precedence over a global variable with the same name

difference between host objects and native objects

a native object is inherent to JS String, boolean host object everything the environment gives you and differ depending on the host window

push()

adds one or more elements to the end of an array and return the new length of arr

Difference between document load event and document ready event?

document load event general "loading complete" signal ex) <iframe src="/"></iframe> <script> document.getElementsByTagName('iframe')[0].onload = function() { alert('loaded') } </script> he ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.

what is the DOM

document object model it is a way to manipulate the structure and style of an HTML page. it represents the internals of the page as the browser sees it we can alter it with js

What's the difference between feature detection, feature inference, and using the UA string?

feature detection used to check if certain feature exisit since different browsers have different implmination feature inference When you make an assumption that because one feature is present (or not) another one will also be present (or not) UA string stands for user agent, which means the browser we can get info like version of chrome by sniffing the user agent string

what is the onerror event handler

first feature to facilitate error handling for JS

read through an array

for (var i = 0; i < x.length; i++) x[i]

anonymous function def

function () { } can assign anon functions to variables and be passed

Difference between: function Person(){}, var person = Person(), and var person = new Person()

function Person() {} declares a function var person = Person() Declares a variable (person), invokes a function (Person) and sets the value of person to the return of the function. var person = new Person() Creates a new instance of an object based on the Person function. So the variable (person) is now an Object, not just a string or a number.

example of closure

function create() { var counter = 0; return { increment: function(){ counter ++; }, print: function(){ console.log(counter); } } } var c = create(); c.increment(); c.print(); ===> 1 the variable function is visible w/in the print and incriminet function

how can you get a reference of a caller function inside another function

function func() { return arguments.calee; }

what is a named function?

function funcName(){ //do stuff here }

what is closure and how to use it

function that has a reference to a private variable function Person(name) { var name = name; //to access name this.getName = function() { return name; }; } we want to use closure when we have nested functions to teach variables that are out of scope

Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

global variables are considered a "bad thing". JS is no different, but it probably has more severe consequences than most languages. JS defaults all variables to the global scope unless they are explicitly defined elsewhere ex) function badlyScoped() { globalVariable = "I'm a global variable"; } badlyScoped(); console.log(globalVariable); // logs "I'm a global variable Conflict with other code. When access global state, component must be aware of environment, which is unpredictable not as contained.

Describe event bubbling.

he concept of event bubbling was introduced to deal with situations where a single event, such as a mouse click, may be handled by two or more event handlers defined at different levels of the Document Object Model (DOM) hierarchy

Why is extending built-in JavaScript objects not a good idea?

if, in future, a browser decides to implement its own version of your method, your method might get overridden (silently) and the browser's implementation (which is probably different from yours) would take over. So not extending in the first place is future proofing your code.

what is IIFE why does this not work? foo(){ }()

immediatly invoked function expression the parser is going to treat this as a function declaration so we fix it with parenthesis around it

how does this work in js?

it holds a reference to the current object

what is Jqueary

its a library used to manipulate the dom we can add it as a script

how does typeof work?

its a unary operator and it indicates the data type evaluates to number string or boolean for a null value it returns an object

what are valid scopes of a variable in JS?

js uses function scope meaning variables are not visible outside of the function global: visible everywhere local: visible w/i a function

advantages of using javascript?

less server interaction: meaning we can validate user input before sending the page off to the server richer interface: meaning we can use js to include items such as dragable components

what is 'this'

referes to the current context

pop()

removes the last elemnt of the array and returns the element

length()

return length of string

indexOf()

returns index of calling string object of the first occirance of specidifed value o/w return -1

substr()

returns substring

"str".charcodeAt(index)

returns the decimal representation of the letter "a".charCodeAt(0) - 97 = 0 a = 97

reverse()

reverses the order of the elements

what is event delegation

simplifies event handling by use of bubbling. attach a single handler to the whole event with event.target

why is it dangerous to typeof bar === "object" to determine of bar is an object

since null is also considered an object so i would add another statement checking to see that bar is not null

sort()

sorts elements

Explain the same-origin policy with regards to JavaScript.

stops code from another site executing on your site. Cross Site Scripting attack. js decides if its the same site if these 3 things are the same: the protocol (http vs. https), the domain (subdomain.yoursite.com vs. yoursite.com vs. google.com), and the port (:80 vs. :4567). If all three of these line up, then JS views the sites as the same, and code is executed. If any of them are different then the code is marked as potentially malicious and is not run.

what is the significance of wrapping the entire source of JS source file in a function block?

to create closure thus creating a private namespace A closure is an inner function that has access to the outer (enclosing) function's variables—scope chain it has 3 scope chains 1: has access to vars w/i its own scope 2: has access to the outer functions variables 3: has access to global variables basic example: function showName(firstName, lastName) { var nameIntro: "your name is: " function makeFullName() { ​return nameIntro + firstName + " " + lastName; } return makeFullName(); } showName("Raya", "Straus");

typical case for anonymous functions

to pass them as arguments to other functions like the map function var numbers = [2,4,6]; var numers_half = numbers.map(function(item) { return item / 2; }); or to create closures (function() { alert('foo'); })();

what are callbacks?

to react to an event we listen for it (onchange) and supply a function which will be called by the browser this function is known as a callback

how to handle execptions in JS

try and catch

how to get a type of argument

use typeof

maps

var myMap = new Map(); myMap.set('foo', 'bar'); console.log(myMap.get('foo')); will print out bar iterate ove a map var value; Object.keys(myMap).forEach(function(key){ value = myMap[key]; console.log(value); });

using a map on an array

var numbers = [1, 4, 9]; var doubles = numbers.map(function(num) { return num * 2; }); // doubles is now [2, 8, 18] // numbers is still [1, 4, 9]

bind

var person1 = {firstName: 'Jon', lastName: 'Kuperman'}; var person2 = {firstName: 'Kelly', lastName: 'King'}; function say() { console.log('Hello ' + this.firstName + ' ' + this.lastName); } var sayHelloJon = say.bind(person1); var sayHelloKelly = say.bind(person2); sayHelloJon(); // Hello Jon Kuperman sayHelloKelly(); // Hello Kelly King Bind is a bit different. It returns a new function. Call and Apply execute the current function immediately.

.apply

var person1 = {firstName: 'Jon', lastName: 'Kuperman'}; var person2 = {firstName: 'Kelly', lastName: 'King'}; function say(greeting) { console.log(greeting + ' ' + this.firstName + ' ' + this.lastName); } say.apply(person1, ['Hello']); // Hello Jon Kuperman say.apply(person2, ['Hello']); // Hello Kelly King

.call

var person1 = {firstName: 'Jon', lastName: 'Kuperman'}; var person2 = {firstName: 'Kelly', lastName: 'King'}; function say(greeting) { console.log(greeting + ' ' + this.firstName + ' ' + this.lastName); } say.call(person1, 'Hello'); // Hello Jon Kuperman say.call(person2, 'Hello'); // Hello Kelly King

what does an XMLHttpRequest look like?

var req = new XMLHttpRequest(); //here we specify a callback function to be called when data is loaded req.onload = function (event) {...}; //put,post... with url //3rd input specifies if the request is asynchronous //usually we dont set it to false bc it will only load when the data is fetched meaning the browser will just be doing nothing for a long time req.open('get', 'some-file.txt', true); req.send();

how do we create an object in JS

var temp = { name: "irena", age: "20" };

how to create an array in JS?

var x = []; var y = [1,2,3];

how to manipulate an id from dom?

we can get it by id document.getElementById ex) var pageHeader = document.getElementById('page-header'); now we can manipulate the pageheader size color

explain how to solve permutation

we can solve it recursively we start out with abc a + permutations of bc b + permuations of ac c + permuations of ab

explain how to do powerSet

were gonna use bit shifting if we look closely we can give each set in the powerset a binary number representation to figure out if the number is in the set we do a logical AND of the two numbers and if the result is greater than zero then the number is in the set

String.fromcharcode(num)

will return the string representation of the number where a = 97

how to print a webpage

window.print()

When would you use document.write()?

writes to the document meaning webpage shouldnt be used after the page has loaded to change the content since it will overwrite the entire page so we use it for third party code like ads

can JS access cookie

yes and it can also manipulate it can modify and delete it


Kaugnay na mga set ng pag-aaral

Final Exam "Which of the following" Questions

View Set

MKTG Exam 2 (quizzes 7.1 - 12.2)

View Set

Geo of Canada Final - Territorial North

View Set