Advanced JavaScript
Advanced JavaScript tests client-side programming: DOM access, events, functions, validation and built-in objects. Questions ask you to trace output, repair a broken handler, or write a short validation routine.
Core rules and concepts
- JavaScript runs in the browser (client side); it can change the loaded page through the DOM.
document.getElementById('id')returns one element;getElementsByClassNameandgetElementsByTagNamereturn collections, so index them, e.g.[0].- Events include
onclick,onsubmit,onchangeandonmouseover. A handler returningfalsecancels the default action, such as form submission. - Declare with
letorconst;varis function-scoped and older. ==compares after type coercion;===compares both value and type.- Useful built-ins:
Math.round(),Math.random(),parseInt(),toUpperCase()andArray.length.
Worked example
A form has <input id='email'> and <form onsubmit='return check()'>. Write the check.
function check(){ var e = document.getElementById('email').value; if(e === ''){ alert('Email required'); return false; } return true; }
Reasoning: .value reads what the user typed; the strict comparison catches an empty string. Returning false stops submission, while true allows it. Without return check() in the attribute, the function's return value is discarded and the form submits anyway.
Traps that cost marks
- Writing
document.getElementById('email').innerHTMLto read an input value. - Forgetting
[0]aftergetElementsByClassName. - Using
=instead of==or===inside a condition. - Placing the script in
<head>and querying elements before they exist. - Expecting
alert()to return the user's input; it returns nothing useful.