JavaScript

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

How to test the time it takes for a function to complete?

console.time('nameWeGiveToTheTimeTest'); --- what we are testing goes inside --- console.timeEnd('nameWeGiveToTheTimeTest')

What line of code can we use to pause at a moment in time and click through each line of the program?

debugger;

How do you add a piece of html code into the document through JS?

document.createElement('etc'); --> var todoLi = document.createElement('li');

How to manipulate DOM through an ID?

document.getElementById(id)

How to manipulate DOM through a class name?

document.getElementsByClassName(className)

How to manipulate DOM through a tag name?

document.getElementsByTagName(tagName)

How do you select something within the document?

document.querySelector('etc'); --> var todosUl = document.querySelector('ul');

How to manipulate DOM through a CSS selector name?

document.querySelector(cssSelector)

Create a callback

downloadPhoto('http://coolcats.com/cat.gif', handlePhoto) function handlePhoto (error, photo) { if (error) console.error('Download error!', error) else console.log('Download finished', photo) } console.log('Download started') --------------------- - handlePhoto isn't called till finished download. 1) handlePhoto function declared 2) DownloadPhoto function invoked 3) 'Download Started' is printed

Which built-in method returns the index within the calling String object of the first occurrence of the specified value?

indexOf();

How do you search an array for a particular value?

indexOf. var something = array.indexOf('word');

Callback (high order function)

A callback is when you call a function as an argument in another function. Asynchronous so it doesn't block.

What is a functor?

Functor is an object that has the map method in it. One of the most common is an array.

Which built-in method combines the text of two strings and returns a new string?

concat();

How to select and change a css style in JS?

var headingEl = document.querySelector("#heading"); headingEl.style.color = "orange";

How to select all images in a web page?

var imgEls = document.getElementByTag("img"); imgEls.src = "url to replace those urls with";

jQuery - Read through these basics

- jQuery is a function, and it has other utility functions bound to it, like ajax and noConflict. - You can pass a function to jQuery as a convenient way of setting up your code in its own scope, and to ensure that your code will execute as soon as the DOM is ready. - You normally pass jQuery a selector and it returns an array of elements, wrapped in a jQuery object. - jQuery objects come with lots of methods for working with the selection of elements they contain. - STYLE: $(selector).method0(args0).method1(args1).method2(args2); $("li").on("click", function(event){ console.log(this) });

Filter method

.filter(); var newArr = arr.filter(function(item){ return item.name === "orange"; });

Map method

.map(); The map() method creates a new array with the results of calling a provided function on every element in this array. return oldArr.map(function(item,index){ item.full_name = [item.first_name,item.last_name].join(" "); return item; });

How to create an event listener for a button click?

// 1. Find and store the element we want to listen to events on. var clickerButton = document.getElementById("clicker"); // 2. Define the function that will respond to the event. // callback var onButtonClick = function() { clickerButton.textContent = "Oh wow, you clicked me!"; }; // 3. Add the event listener for the element and function // anonymous "inline" clickerButton.addEventListener("click", onButtonClick);

Disadvantages of JS

1) Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason. 2) can not be used for Networking applications 3) No multithreading or multiprocess capabilities.

Advantages of JS

1) Less server interaction. 2) Immediate user-feedback, client-side language 3) Increased interactivity, rich interfaces,

What are the 3 rules of callback hell?

1) Name your functions, keep your code shallow. 2) Modularize. Create small modules that do different tasks, then combine to complete large tasks. 3) Always prepare for errors through the error argument.

What is the filter function and how do you do it?

A function on an array that accepts another function as its argument which it will use to return a new filtered version of the array. var animals = [ {name: bob, species: dog} {name: etc, species: etc} ]; var dogs = animal.filter(function(animal) { return animal.species === "dog"; });

Closure

A function that remains available after the outer function has already returned. inside of a function that has access to its parent's scope variables (as well as global scope). Called by Sagas[0] after the function.

When would you use bind?

A good use of the bind function is when you have a particular function that you want to call with a specific this value. You can then use bind to pass a specific object to a function that uses a this reference.

How do you create an Array?

A new array can be created by using the literal constructor []. Arrays can contain different types of objects. For example, the array below contains an Integer, a String and a Float: ary = [1, "two", 3.0] #=> [1, "two", 3.0] An array can also be created by explicitly calling ::new with zero, one (the initial size of the Array) or two arguments (the initial size and a default object). ary = Array.new #=> [] Array.new(3) #=> [nil, nil, nil] Array.new(3, true) #=> [true, true, true] Note that the second argument populates the array with references to the same object. Therefore, it is only recommended in cases when you need to instantiate arrays with natively immutable objects such as Symbols, numbers, true or false. To create an array with separate objects a block can be passed instead. This method is safe to use with mutable objects such as hashes, strings or other arrays: Array.new(4) { Hash.new } #=> [{}, {}, {}, {}] This is also a quick way to build up multi-dimensional arrays: empty_table = Array.new(3) { Array.new(3) } #=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]] An array can also be created by using the Array() method, provided by Kernel, which tries to call to_ary, then to_a on its argument. Array({:a => "a", :b => "b"}) #=> [[:a, "a"], [:b, "b"]] Example Usage¶ ↑ In addition to the methods it mixes in through the Enumerable module, the Array class has proprietary methods for accessing, searching and otherwise manipulating arrays. Some of the more common ones are illustrated below.

What is a promise, why is it important?

A promise is a function that will be called at a later time. Important because promises are composable and callbacks aren't!

How do you add classes to an HTML element in JavaScript?

Add in the class in CSS. Then in JS: nameEls[i].className += " catcolors";

What is an instance?

An instance is an implementation of a Function. In simple terms, it is a copy (or "child") of a Function or object. For example: // Tree is a constructor function because we will use new keyword to invoke it.​ ​function Tree (typeOfTree) {} ​ ​// bananaTree is an instance of Tree.​ ​var bananaTree = new Tree ("banana");

Insertion Sort

Call the first element of the array "sorted", Repeat until all elements are sorted. Look at the next unsorted element, Insert into the 'sorted' position by shifting the requisite number of elements.

You can't use dashes in JS, for example, when you try to select a CSS class? How do you change that format to copy a '-' in css?

Camel case!

Which built-in method returns the character at the specified index?

CharAt();

How do you add one array to another?

Concatenation. var combinedArray = oneArray.concat(otherArray);

How do you access the nth element in an array?

Elements in an array can be retrieved using the #[] method. It can take a single integer argument (a numeric index), a pair of arguments (start and length) or a range. Negative indices start counting from the end, with -1 being the last element. arr = [1, 2, 3, 4, 5, 6] arr[2] #=> 3 arr[100] #=> nil arr[-3] #=> 4 arr[2, 3] #=> [3, 4, 5] arr[1..4] #=> [2, 3, 4, 5] arr[1..-3] #=> [2, 3, 4] Another way to access a particular array element is by using the at method arr.at(0) #=> 1 The slice method works in an identical manner to #[]. To raise an error for indices outside of the array bounds or else to provide a default value when that happens, you can use fetch. arr = ['a', 'b', 'c', 'd', 'e', 'f'] arr.fetch(100) #=> IndexError: index 100 outside of array bounds: -6...6 arr.fetch(100, "oops") #=> "oops" The special methods first and last will return the first and last elements of an array, respectively. arr.first #=> 1 arr.last #=> 6 To return the first n elements of an array, use take arr.take(3) #=> [1, 2, 3] drop does the opposite of take, by returning the elements after n elements have been dropped: arr.drop(3) #=> [4, 5, 6]

What is a factory and how do you make it?

Function that creates and objects and returns it. Should use these over classes.

What does the 'for each' function work? and how to do it?

Goes through each item in an array and does something. function(console) { var names = ["Ben", "Jafar", "Matt", "Priya", "Brian"]; names.forEach(function(name) { console.log(name); }); }

How to convert JS to JSON and JSON to JS?

JSON.stringify converts from JavaScript to JSON. JSON.parse converts from JSON to JavaScript.

Bubble Sort

Move higher valued elements to the right and lower valued elements to the left. 1) Set swap counter to non zero value. 2) Repeat until swap counter is 0: then 3) reset swap counter to 0. 4) Look at each adjacent pair. 5) If two adjacent elements are not in order, swap them and add one to the swap counter.

Selection Sort

Repeat until no unsorted element remain: 1) Search unsorted part of data to find smallest value. 2) Swap smallest value with first element of unsorted part.

What does "use strict" do?

The "use strict" literal is entered at the top of a JavaScript program or at the top of a function and it helps you write safer JavaScript code by throwing an error if a global variable is created by mistake.

What is the higher order 'find' function and how to do it?

The Find function works exactly like the filter function but *ONLY* returns the very first one it finds. :) Only works on an array.

Bind

The bind method, which all functions have, creates a new function that will call the original function but with some of the arguments already fixed.

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

The difference is that == performs implicit type conversion to check if values are equal to each other. This can really cause some problems when you're writing JavaScript, so the safe thing to do is use the triple equal operator instead, which checks that the two values are of the same type and does not perform type conversion.

Prototype, why do you use it? Syntax?

We use prototypes when there are functions inside of a constructor so that it isn't called for every single instance created. Object.prototype.propertyFunction = function () { function goes here }

What is recursion?

When a function call itself until it doesn't. var countDownFrom = function(num) { if (num === 0) { return; } console.log(num): countDownFrom(num - 1); } countDownFrom(10);

What is currying?

When a function does not take all of its arguments up front. The function will return another function which will be called with a second argument. and so on until all arguments have been provided. One way to call a very nested list of functions is this: console.og(dragon('fluffyName')('tiny')('lightning'));

What is inheritance and how do you use it?

Written as a constructor, but called within the other constructors like: inheritanceName.call(this, etc, etc); Then have to create connection to the related proto. constructorName.prototype = Object.create(inherName.prototype);

Inheritance

an object being able to inherit methods and properties from a parent object (a Class in other OOP languages, or a Function in JavaScript).

How do you return selected elements in an array, as a new array?

arr.slice(start, end); .slice does not change the orig. array.

How do you add/remove items to/from an array, and return the removed item(s).

arr.splice(start, number to be added or removed, "str if adding", "str if adding"); Splice does change the orig. array.

How do you turn an array into a string?

arr.toString();

How to swap two numbers without a temp var:

b = b -a; a = a+ b; b = a-b;

Encapsulation

enclosing all the functionalities of an object within that object so that the object's internal workings (its methods and properties) are hidden from the rest of the application. This allows us to abstract or localize specific set of functionalities on objects.

Which built-in method calls a function for each element in the array?

forEach();

What is a constructor and how do you make it?

function Contact(name, email) { this.name = name; this.email = email; this.sendEmail = function() { Do something } } var contact1 = new Contact("Andrew", "[email protected]");

How would you check if a number is an integer?

function isInt(num) { return num % 1 === 0; }

Write a function that would allow you to do this. multiply(5)(6);

function multiply(a) { return function(b) { return a * b; } } multiply(5)(6);

Is finite function

isFinite(); Checks to see if it's a real number.

What are four of the most common JS 'Events'?

mouse events, touch events, keyboard events, form events: focus, blur, change, submit window events: scroll, resize, hashchange, load, unload

How do you delete an item from the end of an array?

myArray.pop();

How do you add an item to an array?

myArray.push(etc);

How do you reverse an array?

myArray.reverse();

How do you delete an item from the beginning of an array?

myArray.shift();

How do you sort an array in alphabetical order?

myArray.sort();

How do you add an item to the beginning of an array?

myArray.unshift(etc);

Six different types of values in javascript?

numbers, strings, Booleans, objects, functions, and undefined values.

.ParseInt(value);

parseInt(value); turns a string argument into an integer.

How to delay, in syntax, a function.

setTimeout(yourFunction, 3000);

How to check whether a string ends with a certain character.

str.endsWith("x", 11 -- length of string);

How to check whether a string includes a certain character?

str.includes("x");

map

to build a new array where each element has been put through a function. The map method transforms an array by applying a function to all of its elements and building a new array from the returned values. The new array will have the same length as the input array, but its content will have been "mapped" to a new form by the function. var animals = [ {name: bob, species: dog} {name: etc, species: etc} ]; var names = animals.map(function) { return animal.name; });

What does the reduce method do, and how to use it?

to combine all an array's elements into a single value. -- function (array, combined, start) -- can leave off 'start'. BUT reduce can be used to do ANY array transformation. The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value. var orders = [ { amount: 250 }, etc ] var totalAmount = orders.reduce(function (sum, order) { return sum + order.amount; }, 0);

.forEach();

to do something with each element in an array

Which built-in method returns the string representation of the number's value?

toString();

How to use the map method, ie how to take 3 strings and get their lengths?

var animals = ["cat","dog","fish"]; var lengths = animals.map(function(animal) { return animal.length; }); console.log(lengths); //[3, 3, 4]

How to use the reduce method, ie how to take 3 strings and get the total length?

var animals = ["cat","dog","fish"]; var total = animals.reduce(function(sum, word) { return sum + word.length; }, 0); console.log(total); OR var animals = ["cat","dog","fish"]; var total = animals.reduce(function(sum, word) { return sum + word.length; }, 0); console.log(total);

How do you return an array with the entire list, as a string, separated by a character?

var arrayString = array.join(', '); or just array.join(', ');

How would you get the day in the month?

var currentDay = getDate(); --> 1 to 31

How would you get the current month?

var currentMonth = getMonth(); --> 0 to 11

How do you create a variable with the current date and time?

var currentTime = new Date();

How would you get the current year?

var currentYear = getFullYear();

How to do a query selector to all links that have "Dog" in it?

var linkEls = document.qeurySelectorAll("a[href*=\"Dog\"]"); then for loop through -> linkEls[i].href = "http://en.wikipedia.org/wiki/Cat";

How do you create an object (syntax)?

var object = { name: "dave", grades: [90, 50, 75] };

accumulate method

var result = accumulate(aray); adds all numbers in an array


संबंधित स्टडी सेट्स

IT 206 Quiz 2 Study Guide & Final Review

View Set

Directed Reading: Exchange with the Environment

View Set

17 - LEGAL, ETHICAL & MORAL ISSUES OF HEALTH CARE

View Set