Exploring the contrast in scoping between variables and objects within javascript

Could someone please elaborate on the distinction between these two sets of JavaScript code snippets?

var orange = { prop: "I am a simple fruit"};

console.log(orange.prop);  //output: "I am a simple fruit"

function go(orange) {
    orange.prop = "Now I have been changed by the function";
};

go(orange);

console.log(orange.prop); // output: "Now I have been changed by the function"

.
In the block above, the go function clearly modified the orange object in the outer scope
.

var apple = "I am a simple apple";

console.log(apple); // output "I am a simple apple"

function goApple(apple) {

    apple = "Now I have been changed by the function";

};

goApple(apple);

console.log(apple); // output "I am a simple apple"

In this block, the initial apple variable remains unchanged
I seem to be overlooking something fundamental and obvious here, or could it be that JavaScript follows different scoping rules for various variable types?

Answer №1

The main distinction is in the nature of the argument you provide.

typeof banana //"string"
typeof strawberry //"object"

By passing string literals, you are actually passing data that cannot be changed, and it is transmitted by value, thereby maintaining its original state.

UPDATE: In other words, the information pointed to by window.banana remains constant. To modify window.banana, it must be redirected to a different dataset. window.banana = "fresh data";

Answer №2

Here is a quick breakdown:

const grabApple = (apple) => {

The function above takes in an argument called apple, which essentially creates a local variable within the function scope. Any changes made to this variable inside the function will only affect this local copy, not the original one outside.

A similar concept applies when dealing with the orange argument. You are also creating a local variable, but any modifications you make to it would only impact its properties rather than the actual value of the outer orange object.

Answer №3

When it comes to passing function parameters in Javascript, they are always passed by value. However, there is an exception when dealing with objects. In this scenario, if you are accessing a property of an object that is passed as a parameter, it will be passed by reference. This means that when the object (let's say apple) is passed to the function, a copy of its reference is created and assigned to another variable (let's call it orange). As a result, both variables now point to the same object in memory.

Answer №4

To improve clarity, consider using different names for your function arguments than your global variables. The current setup of using apple and orange both as global variables and argument variables can lead to confusion as they overshadow the outer globals within the function.

var apple = "i am a simple apple";
console.log(apple); // output: "i am a simple apple"

function updateApple(appleArg) {
    appleArg = "Now I have been changed by the function";
};

updateApple(apple);
console.log(apple); // output: "i am a simple apple"

In the above example, you are only changing the reference that appleArg points to; this does not affect the value referred to by the outer variable apple.

Contrastingly, in the case of modifying the object itself like with orange:

var orange = { prop: "i am a simple fruit"};
console.log(orange.prop);  //output: "i am a simple fruit"

function update(orangeArg) {
    orangeArg.prop = "Now I have been changed by the function";
};

update(orange);
console.log(orange.prop); // output: "Now I have been changed by the function"

In this scenario, both orange and orangeArg point to the same value and do not change their references. However, the actual value (object properties) is modified without affecting the reference.

Remember, primitives like strings cannot be directly modified due to immutability, while objects allow modification of their properties. As shown below:

var mango = { prop: "i am a simple fruit"};
console.log(mango.prop);  //output: "i am a simple fruit"

function alter(mangoArg) {
    mangoArg = { prop: "Now I have been changed by the function" };
};

alter(mango);
console.log(mango.prop); // output: "i am a simple fruit"

In this last illustration, we altered mangoArg to point to a completely new value, instead of modifying the object referenced by mango.

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

Customized function enabling dynamic menu display based on varying screen dimensions

Looking for assistance with JS and jQuery as I am relatively new to it. Any help would be greatly appreciated... I'm currently working on a responsive header where I want to implement onclick functions for mobile and tablet resolutions only. I' ...

Angular throwing an error: "Unknown provider. Nested controllers"

I am facing an issue with calling a method in another Angular controller. There is a separate Angular app on the webpage, and I need to utilize some functionality from that app. However, when I include the other controller in my HTML file, I encounter the ...

Creating URLs in asp.net using both name and ID parameters

test.Controls.Add(GetButton(thisReader["session_id"].ToString(), "Join Session")); I made a modification to the code above, switching it to: test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session")); The reason for this change ...

The functionality of the typeof operator is not behaving as anticipated

I am currently working on a script to verify the existence of a specific JavaScript object. var success = function(data) { var x= 0; var numOfCards = data.length; for (x=0;x<data.length - 1;x++) { if (typeof data[x].l ...

Encountering a 400 BAD REQUEST error while attempting to make an AJAX post request in

I'm struggling to grasp the concept of AJAX and I'm perplexed as to why this code snippet isn't functioning properly. When making an AJAX call, I keep encountering a 400 BAD REQUEST error, but the cause eludes me. Below is the AJAX functio ...

Javascript - Array checking for overlapping numeric ranges

I am currently working with an array of time ranges that have both start and end values. var timeRanges = [{ start: 120, end: 140 },{ start: 180, end: 220 },{ start: 250, end: 300 }] My task requires me to determine if the selecte ...

javascript Adjust background according to the current time

Hey there! I've been experimenting with javascript lately and am working on a project where I want the website background to change based on whether it's Day or Night. However, when I test the page, it seems to be skipping over my code and going ...

Finding the precise identifier of the selected input from a list with JQUERY

I need help with using jquery to correctly identify the button that I'm clicking. I have a list of dynamically generated categories with Remove buttons to delete them from the database. Here are my input examples: <input id="deletesector" class= ...

What is the best way to create an array of randomized numbers with a variance of 1 using JavaScript?

I am looking to create an array similar to the following structure using javascript: [ 52, // random number 0-100 53, // random +1 or -1 54, // random +1 or -1 53, // random +1 or -1 52, // random +1 or -1 53, // random +1 or -1 52, // random ...

What is the most effective method for disregarding undefined values?

Implementing a project using Vue.js and Vuex, I am retrieving data from an API that functions as a content-management system. The product class in the CMS possesses numerous properties that can be populated by the user, such as; { "title": &quo ...

Can you explain the variance in these code snippets when implementing React's setState() function?

Can you explain the variance between these two blocks of code? this.setState((state)=>({ posts: state.posts.filter(post=> post.id !==postRemoved.id) })) versus this.setState((state)=>{ posts: state.post ...

Every time I refresh a Next.js page, I find myself back on the index.js

I find it confusing that whenever I refresh a page in my Next.js app, it always redirects me back to the index page. My e-commerce single-page application (SPA) has a catalogue page in index.js and the products are displayed using the dynamic [name].js pag ...

How can you personalize a website script by deactivating it using uBlock Origin and then reintegrating it as a userscript?

Can you imagine if it were possible to address a problematic portion of a script on a website by preventing the original script from loading, copying the source code, editing it, and then re-injecting it as a userscript with Tampermonkey? I attempted this ...

Building blocks & lists in markup language

I've created my constructor and array, but I'm unsure how to display it in the HTML file. It involves a plus/minus show/hide feature. Below is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> ...

Loading JSON models with raycasting and colliding with meshes in three.js

Currently, I am utilizing a raycaster to detect if the mouse (or touch) hits a mesh. The object is slender and I would like to enlarge the size of whatever can be intersected by the Ray. While working with game objects in three.js, is there a way for me to ...

Is there a different way to access a PHP page besides using a hyperlink? I've tried that method but it doesn't seem to

Within my side navbar, I have a dropdown menu with sub-menus for each option. My directory structure is as follows: RBS | +-- All php files are located here |--one.php |--two.php | +-- css | | | +-- all css files are stored here | + ...

Display or conceal several elements using JQUERY/HTML upon hovering

Here is the current progress: <div style="position: relative;"> <a href="#games"> <div class="sidenavOff"> <img src = "images/card_normal.png" /> <img src = "images/category_icons/icon_games.png" style = "position: a ...

Activate a function for a targeted ajax request within a global $.ajax event

I have a series of 3-4 ajax calls that are scheduled to be executed at some point. In one of these calls, I want to activate a function on the global ajaxSend event. This particular ajax call may not be the first or last in the sequence. However, when I at ...

Newbie to Angular encounters issue with Yeoman: failure to define 'app'

I created a task list that you can view here: https://github.com/EdmundMai/angular_todolist Within my controller, I am able to globally access the toDoListApp anywhere I like. Now, as I embark on a new project using Yeoman, I find myself in a similar set ...

Is there a way to identify a change in the URL using JQuery?

My goal is to clear the localStorage when a user navigates to a different page. For instance, if I am currently on . When the user goes to the URL, , I want to clear the localStorage. This is my script using JQuery. $(window).unload(function(){ if ...