Chetan Wadhwa
Chetan Wadhwa

Reputation: 1

Why we use "var" instead of String or Number or Boolean (primitives) in javascript?

Why we use "var" when we have String , Number and Boolean primitives in javascript.

var str = 'Sample String';

String str = 'Sample String';

What is the best practice and why ?

Upvotes: 0

Views: 265

Answers (2)

Hacketo
Hacketo

Reputation: 4997

var in javascript is used to declare a local variable

var myVariable = "";          // Local scope Variable

myVariable = "";              // Declare on Global scope window.myVariable (if not declared in the local scope)

String str = 'Sample String'; // Throw SyntaxError

So if you want to declare a variable you should use the var keyword, else you could reach some mistake when you think you are using a local variable like this :

 for (i = 0, i < 10 ; i++){ // Global variable i === window.i

Upvotes: 0

raina77ow
raina77ow

Reputation: 106375

Why we use var instead of String?

Because JavaScript is a dynamically typed language by design. A variable named str might store a String when initialized, but a Number (or value of any other type) later: types won't be checked at any point. When the language was created, it was considered an advantage.

In fact, we only use var to make a specific name local to a specific scope; it's highly recommended, but not even required (unless 'strict mode' is on). Using String (or any other type name - actually, the name of the corresponding constructor function) would cause a syntax error.

Upvotes: 4

Related Questions