Javascript Flashcards
What are the 4 ways we can write messages in Javascript?
1) Writing into an HTML element, using innerHTML.
2) Writing into the HTML output using document.write().
3) Writing into an alert box, using window.alert().
4) Writing into the browser console, using console.log()
How to get an element by ID?
document.getElementById(id)
What is the disadvantage of document.write()?
Never call document.write after the document has finished loading. It will overwrite the whole document. The document.write() method should only be used for testing.
Find the type of a JavaScript variable with…
typeof
Example o JavaScript object
var person = {firstName:”John”, lastName:”Doe”, age:50, eyeColor:”blue”};
How can I set a value to empty in JS?
By setting the value to undefined. car = undefined; // Value is undefined, type is undefined; or by suing NULL. person = null; // Now value is null, but type is still an object
Example of complex object
var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } };
Example of event handling
Common JS events
onchange: An HTML element has been changed
onclick: The user clicks an HTML element
onmouseover: The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown: The user pushes a keyboard key
onload: The browser has finished loading the page
Comparing two JavaScript objects will always return false
because they are different objects in memory
What does the === do?
operator expects equality in both type and value
What does the method lastIndexOf() do?
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string
What does the method search() do?
The search() method searches a string for a specified value and returns the position of the match
What is the difference between substring() and slice() methods?
substring() is similar to slice(). The difference is that substring() cannot accept negative indexes
How to replace values (case insensitive mode)?
To replace case insensitive, use a regular expression with an /i flag (insensitive): str = "Please visit Microsoft!"; var n = str.replace(/MICROSOFT/i, "W3Schools");
How to replace all matches?
use a regular expression with a /g flag (global match). str = "Please visit Microsoft and Microsoft!"; var n = str.replace(/Microsoft/g, "W3Schools");
How to concatenate strings?
concat() var text1 = "Hello"; var text2 = "World"; var text3 = text1.concat(" ", text2);
JS rounding method
var x = 9.656;
x. toFixed(0); // returns 10
x. toFixed(2); // returns 9.66
x. toFixed(4); // returns 9.6560
x. toFixed(6); // returns 9.656000