Creating a variable by using a conditional operation in JavaScript

When the statement <code>name = name || {}
is used, it throws a reference error. However, using var name = name || {} works perfectly fine. Can you explain how variable initialization in JavaScript functions?

Answer №1

When looking at the code line:

var name = name || {};

it is important to understand that this is actually interpreted as follows:

// Upon entering the scope
var name;

// Later on, in step-by-step execution
name = name || {}

Since name is declared, it is safe to access its value (using name on the right side of the = operator). Initially, the value will be undefined, so name = name || {} will assign an empty object to it.

The significant distinction here lies in the fact that:

name = name || {}

...does not have a declaration for name, meaning that the variable does not exist when the right-hand side of the assignment is evaluated. This concept of creating global variables implicitly through assignments, as discussed in The Horror of Implicit Globals, allows you to create global variables but prevents you from reading the value of a non-existent variable.

Therefore, using var ensures proper functioning, while omitting it results in a ReferenceError.


As a side note, it is advisable to refrain from relying on implicit globals and always declare your variables explicitly (while minimizing the use of globals whenever feasible). Enabling JavaScript's "strict mode" can transform implicit globals into ReferenceErrors, thereby treating attempts to write to unknown symbols as errors instead of creating new global variables, similar to the behavior for reading undefined symbols.

Answer №2

The effectiveness of the second code lies in the concept of JavaScript Hoisting.

Consider this scenario:

var person = person || {}

With hoisting, the code is rearranged as follows:

// Declaration moved to the top of the scope
var person;

// Initialization point
person = person || {};

As a result, when you initialize the variable 'person,' it has already been declared with an initial value of undefined. In contrast, the first code does not explicitly declare 'person'.

Answer №3

name = name || {} means "If the variable name already exists, set it to itself, otherwise set it to an empty object. The issue here is that you actually do not have a variable named name yet. So, when the code checks what value to assign to it, it encounters an error because it hasn't been defined.

var name = ... first declares the variable and then assigns a value to it. This approach avoids the error by creating the variable before evaluating its value. Therefore, if the variable doesn't exist, it defaults to being undefined, which can be considered falsey and set to an empty object.

This situation commonly arises in two other scenarios as well.

function a(name) { name = name || 'Joe'; }

In this function, if no argument is provided for name, it defaults to 'Joe'. Since the variable is already defined within the function argument, there is no need to use var.

defaults = { name: 'Joe' };
options = {};

// Later on
options.name = options.name || defaults.name;

Answer №4

When utilizing the var keyword in JavaScript, it is important to declare all variables at the beginning of the scope due to a concept known as variable hoisting.

As an illustration, consider the following code snippet:

function doStuff() {
   for (var i = 0; i < arr.lenght; i++)
      var currentItem = arr[i]
      var doSomething = function(currentItem) { ... }
   }
}

JavaScript actually interprets this code in the following manner:

function doStuff() {
   var i,
       currentItem,
       doSomething;

   for (i = 0; i < arr.lenght; i++) {
      currentItem = arr[i]
      doSomething = function(currentItem) {...}
   }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Not motivated to write HTML content

Recently, I've been utilizing the lazySizes plugin for optimizing my images. However, I encountered an issue when trying to implement it for HTML content display. Is there a simpler way to achieve this and maintain my current HTML structure? $(&apo ...

Ways to collapse all rows that are expanded except the one that is currently open in iView Tables

Utilizing iView Tables to display data in a table with an expand option. As of now, when clicking on the expand button for a row, the row expands but previously expanded rows do not collapse, causing all expanded rows to be visible at once. Is there a wa ...

Uploading a JSON file to myjson.com using a jQuery PUT request in Node.js

As a novice in javascript, I have successfully retrieved a JSON object from on my HTML page using AJAX with the following code: $.getJSON("https://api.myjson.com/bins/bjm28", function (data) { $.each(data, function (index, value) { console.log ...

Convert the JSON data into the specified format using JavaScript

Is there a way to transform JSON data like this in JavaScript? data = [{acquired: "2018-03-09T22:49:52.935Z", mean_ndvi: -0.0483685} {acquired: "2018-02-13T22:49:16.568Z", mean_ndvi: 0.00595065} {acquired: "2018-04-01T22:50:30.912Z", mean_ndvi: -0.033455} ...

Automate CSS slideshow playback using JavaScript

Using only CSS, I created a basic slideshow where the margin of the element changes upon radio button click to display the desired slide. You can view the functionality in the code snippet below. Additionally, I implemented auto play for this slideshow usi ...

Use Material UI TextField to prompt an email client or make a phone call

I am facing an issue with a MaterialUI TextField component. In certain situations, the TextField is disabled and I want it to be clickable as if it were an anchor tag leading to a phone number or email address. However, it seems that making the input behav ...

What's causing the problem with my custom filter?

I've encountered an issue with a custom filter I'm currently working on. The challenge lies in the fact that I'm using Angular 1.3.6 and am unable to upgrade at the moment. Therefore, I truly need your assistance with this matter. Check out ...

Creating a read-only DIV using Angular - a step-by-step guide

Is there a simple way to make all clickable elements inside a div read only? For example, in the provided HTML code, these divs act like buttons and I want to disable them from being clicked. Any tips or shortcuts to achieve this? Thank you. #html < ...

Autocomplete failing to provide a valid response, returning a null value instead

Utilizing an Autocomplete feature for employee search, users can input a name and select from the list of results. However, the current onChange function logs the index value instead of the selected employee's name. Is there a way to pass the employee ...

Displaying a page with dynamic data fetched from the server-side to be utilized in the getInitialProps method of

As a newcomer to next.js, my goal for my project is to connect to a database, retrieve data, process it using express, and then utilize it on the client side of my application. I plan to establish a connection to the database within the express route han ...

The bootstrap datepicker does not display the date range on the calendar

I tried to incorporate a bootstrap datepicker date-range in the code snippet below, but I am encountering an issue where the selected date range is not displaying on the calendar. <!DOCTYPE html> <html> <head> <link rel="stylesheet" ...

Insert text into the cursor location within Summernote using JQuery

Currently, I am working on a flutter application where I have implemented the summernote editor using JQuery. ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain); String txtIsi = data.text .replaceAll("'", '\&bsol ...

Having trouble with overriding an @media query for material-ui react components?

I've been trying to modify a @media CSS rule on a Material UI component, similar to the discussions on How to over-ride an @media css for a material-ui react component and Override components like MuiTab that use media queries. However, I have not bee ...

Displaying a static image on an HTML5 canvas without any movement

As a novice in canvas game development, I must apologize for my lack of knowledge. I have an image with dimensions 2048px width and 1536px height that needs to be placed within a canvas (the width and height vary on different devices). While I am able to ...

Should I generate an array or pull data directly from the database?

Hey there, I've got this JavaScript app and could really use some input or tips. Here's the idea: Users log in to try and defeat a 'boss', with each player working together in the game. Let's say the 'boss' has 10 millio ...

Is there a way to automate the duplication/copying of files using JavaScript?

I have a GIF file stored in the "assets" directory on my computer. I want to create multiple duplicates of this file within the same directory, each with a unique filename. For example: If there is a GIF file named "0.gif" in the assets directory, I woul ...

Using the application router in Next.js to implement getServerSideProps()

I recently delved into utilizing Next.js 13 with the App Router, but encountered some challenges. The structure of my test application is as follows: ---/school ------/app ------/layout.tsx ------/page.tsx ---/src The ./app/page.tsx code snippet is ...

Error Module in Angular 1.4.2: $injector:modulerr

I have exhausted all the solutions available on StackOverflow and other sources, but none of them seem to work for me. I have ensured that all scripts are loaded properly. I am using Visual Studio 2015 and trying to create a menu using Mobile Angular Ver ...

Storing Json data in a variable within Angular 2: a step-by-step guide

https://i.sstatic.net/2QjkJ.png Within the params.value object, there are 3 arrays containing names that I need to extract and store in a variable. I attempted to use a ForEach loop for this purpose, but encountered an issue. Can you spot what's wron ...

Activate a function to focus on an input field once ngIf condition becomes true and the input is revealed

I am currently attempting to focus the cursor on a specific input field that is only displayed when the condition of the surrounding ngIf directive is true. Here is an example of the HTML code structure: <div> <button (click)="showFirst = ...