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
Example of forEach loop
var fruits, text;
fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
text = “<ul>”;
fruits.forEach(myFunction);
text += “</ul>”;
function myFunction(value) { text += "<li>" + value + "</li>"; }
shift()
removes the first array element and “shifts” all other elements to a lower index
unshift()
adds a new element to an array (at the beginning), and “unshifts” older elements
splice()
used to add new items to an array
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.splice(2, 0, “Lemon”, “Kiwi”);
splice() with no extra parameters
remove elements without leaving “holes” in the array.
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.splice(0, 1); // Removes the first element of fruits
JS sorting
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits. sort(); // First sort the elements of fruits
fruits. reverse(); // Then reverse the order of the elements
custom sorting
cars.sort(function(a, b){return a.year - b.year});
map()
var numbers1 = [45, 4, 9, 16, 25]; var numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) { return value * 2; }
filter()
var numbers = [45, 4, 9, 16, 25]; var over18 = numbers.filter(myFunction);
function myFunction(value, index, array) { return value > 18; }
Write the code for adding new elements dynamically
t1
function addNode() { var newP = document.createElement("p"); var textNode = document.createTextNode(" This is a new text node"); newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); }
<p>firstP</p>
<p>
</p>
What are JavaScript Data Types?
Number String Boolean Object Undefined
Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer, if any?
Timers are used to execute a piece of code at a set time or also to repeat the code in a given interval of time. This is done by using the functions setTimeout, setInterval and clearInterval.
The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay. The setInterval(function, delay) function is used to repeatedly execute the given function in the mentioned delay and only halts when cancelled. The clearInterval(id) function instructs the timer to stop.
Timers are operated within a single thread, and thus events might queue up, waiting to be executed.
What is the difference between ViewState and SessionState
‘ViewState’ is specific to a page in a session.
‘SessionState’ is specific to user specific data that can be accessed across all pages in the web application.
how can you submit a form using JavaScript?
document.form[0].submit();
How can the style/class of an element be changed?
document.getElementById(“myText”).style.fontSize = “20”;
or
document.getElementById(“myText”).className = “anyclass”;
Explain how to detect the operating system on the client machine?
In order to detect the operating system on the client machine, the navigator.platform string (property) should be used.
or
The ‘Navigator.appversion’ is used to find the name of the operating system in the client machine.
What are all the types of Pop up boxes available in JavaScript?
Alert
Confirm and
Prompt
What is the use of Void(0)?
Void(0) is used to prevent the page from refreshing and parameter “zero” is passed while calling.
Void(0) is used to call another method without refreshing the page.
How can a page be forced to load another page in JavaScript?
<!-- location.href="http://newhost/newpath/newfile.html"; //-->
What is the difference between an alert box and a confirmation box?
An alert box displays only one button which is the OK button.
But a Confirmation box displays two buttons namely OK and cancel.
What are JavaScript Cookies?
Cookies are the small test files stored in a computer and it gets created when the user visits the websites to store information that they need. Example could be User Name details and shopping cart information from the previous visits.
Mention what is the disadvantage of using innerHTML in JavaScript?
Content is replaced everywhere
We cannot use like “appending to innerHTML”
Even if you use +=like “innerHTML = innerHTML + ‘html’” still the old content is replaced by html
The entire innerHTML content is re-parsed and build into elements, therefore its much slower
The innerHTML does not provide validation and therefore we can potentially insert valid and broken HTML in the document and break it
Which keyword is used to print the text in the screen?
document.write(“Welcome”) is used to print the text – Welcome in the screen.
What is the ‘Strict’ mode in JavaScript and how can it be enabled?
Strict Mode adds certain compulsions to JavaScript. Under the strict mode, JavaScript shows errors for a piece of codes, which did not show an error before, but might be problematic and potentially unsafe. Strict mode also solves some mistakes that hamper the JavaScript engines to work efficiently.
Strict mode can be enabled by adding the string literal “use strict” above the file. This can be illustrated by the given example:
function myfunction() {
“use strict”;
var v = “This is a strict mode function”;
}
What is the way to get the status of a CheckBox?
alert(document.getElementById(‘checkbox1’).checked);
Explain window.onload and onDocumentReady?
The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed.
onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.
How will you explain closures in JavaScript? When are they used?
Return a function and save it in a variable then call te variable
How can a particular frame be targeted, from a hyperlink, in JavaScript?
<a>>New Page</a>