JavaScript is client side programming language used for all type of web application development, and there are many different JavaScript frameworks, here are some of commonly asked JavaScript Interview Questions and answers for Beginners.
There are various JavaScript frameworks; here we focus on core JavaScript fundamental questions only.
// for Single line commentMulti line comment example
/* Multi line comments */
<script src="~/Scripts/jquery.validate.js"></script>
var k; var K; // different ;
var name is not defined
.
var a; // declaring x console.log(a); //output: undefined
Now if we try to user some variable that has not been declared before
var a; // Declaration console.log(b); // Output: ReferenceError: b is not defined
var Employee = function (name, org, salary) { this.name = name || ""; //attribute default value is null this.organization = org || ""; this.salary = salary || 5000; } var emp1 = new Employee("Bill","Microsoft",3000); var emp2 = new Employee("Whitney","IBM",5000);
var colors = ['red','blue','orange','while','black','green'];Learn more about JavaScript Array with example
<script> var helloWorld = function () { alert("Anonymous function invoked"); } helloWorld(); </script>Learn more about JavaScript Function with example
'\n'
, at the end of each line.
console.log("Hello World! \n I am ready for next day!"); // OR document.write("Hello Friend! \n How are you doing?");
In above statement line will be broken to next line wherever \n
found, Make sure code is within script tag.
We can write async function in javascript using async
keyword.
let checkUser = async function(username, password){ try { //let result = setTimeout(() => console.log("Tick"), 500); console.log("Welcome "+ username); throw new Error("some error message"); //return result; } catch (ex) { console.log(ex) } };
Look at the example below, where I am calling the above async function from below async function using await keyword.
Notice, the linelet result= await checkUser("u1","p1");
async function myAsyncMethod() { try { let result= await checkUser("u1","p1"); console.log(result); } catch (e) { console.error(e); } finally { console.log('we reached finally block'); } }
Learn more about JavaScript Async Function with example
=
, double ==
and triple ===
?
Single =
is used for assigning value, right to left
Double ==
is for comparing the value
Triple ===
is for comparing value with type
if (2=="2") { console.log("2=='2' is true"); } if (2==="2") { console.log("2==='2' is true"); } else { console.log("2==='2' is false"); } var bar = null; console.log(typeof bar === "object");
var subjectArray = ["JavaScript", "JSON", "Asp.Net Core", "PHP"]; subjectArray.forEach(fetch); function fetch(item, index) { console.log(index + ":" + item ); }
We also can write like example below.
subjectArray.forEach(function (fetch) { console.log(fetch); });
In following student variable, we can store different type of data like name (string), age (integer) etc.
var student= {name:"Arayan Bose",age:29, batch:"XII"}; console.log(student.name);
Cookie is the small piece of data in plain text, each cookie contain data in name-value pair.
In JavaScript we can access cookie object through document.cookie
.
To retrive all cookies, we can write code using document.cookie
like below.
var _cookies = document.cookie; document.write("All Cookies : " + _cookies); //To split all cookies pairs in an array. cookiearray = _cookies.split(';');
document.cookie.length
will get you the length of cookies.
Write following code to create cookie in JavaScript.
var _siteTitle = "Learn JavaScript Free"; var _cookieValue = escape(_siteTitle) + ";"; document.cookie = "title=" + _cookieValue; var _cookies = document.cookie; document.write("All Cookies : " + _cookies);
To change any property of any html element we can access the html element either by id or by name, here in example we change the button property value accessing by id.
Notice, the button text will become "Click Me" to "Have Fun".
<input type="button" id="btnSave" value="Click Me!" onclick="ChangeText();" /> <script type="text/javascript"> function ChangeText() { var btn = document.getElementById("btnSave") btn.value = "Have Fun!"; } </script>
document.form[0].submit();
document.form[0].submit();
Instead of index value, we also can use the form id to submit form-using JavaScript.
like $("#frm1").submit();
\
, is used when working with special characters
like single quotes, double quotes, apostrophes and ampersands, we place \
backslash
before the character to make it display.
JavaScript Regular expressions is a powerful way of doing search and replace in any strings, a regular expression describes a pattern of characters.
Learn more about Regular Expresssion in Javascript.Math.pow(x, y)
There are many built-in math functions in javascript, pow is one of them.
const wait = time => new Promise((resolve) => setTimeout(resolve, time)); wait(5000).then(() => console.log('Hello World!'));
var d = new Date()
, example code will get the current date of the system.
<script> var d = new Date(); document.write("Date is" + d.getDate());<br /> </script>// date result here
We find date, time, seconds, month, year using the same date object in javascript, learn more about JavaScript Date function with examples.
ES6 or ECMAScript is the advanced version of javascript, now we can do more object oriented javascript programming in ES6, which was not possible with earlier javascript version.
We can do stuff like import, export, define class, inheritance, arrow function etc. Learn more about ES6 features
class
keyword, we also can define constructor
Using same constructor
keyword,
take a look at following javscript class example.
class Car { constructor(modelName) { this.modelName = modelName; } checkOil() { console.log(this.modelName + ' is Checking Oil'); } }
You can check more about Object oriented programming in JavaScript at JavaScript class oops example in ES6.
JavaScript has been evolved and more advanced than before, There are many JavaScript frameworks for developing modern efficient web application, so as an experienced JavaScript developer, one must know some of the latest JavaScript trends and framework, here are some interesting JavaScript questions that may help you to get ready for interview.
var fs = require('fs'); var localDir = './staticfiles1'; if (!fs.existsSync(localDir)){ fs.mkdirSync(localDir); console.log("new directory has been created"); }
Here is an example of how you can work with file system in javascript Node JS application.
var con = mysql.createConnection({ host: "localhost", user: "username", password: "password", database: "mydatabaseName", port:"0001", multipleStatements: true });
Here is an example of how to work with MySql database in NodeJs application.
<script> $(document).ready(function(){ $("#btnInfo").click(function(){ $.ajax( { url: "page-or-view-name", data: JSON.stringify(model_data), type:"post", dataType: "json", success: function(result){ $("#div1").html(result); } }); }); }); </script>
Here is an JQuery Ajax Post Example