Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarify my understanding of a bit of JavaScript

Tags:

javascript

I am working through a book that is all about functional javascript. In that book, there is the following bit of code:

const forEachObj = (obj,fn) =>{
    for(let prop in obj){
        if(obj.hasOwnProperty(prop)){
            fn(prop,obj[prop]);
        }
    }
};

I understand this as going through each property of an object then asking IF that object has that property then running a provided function.

What I don't understand is how the if does anything. Won't it always be true? Isn't it just asking if the prop it got from obj is a property of the obj?

like image 813
twodox Avatar asked Feb 25 '19 20:02

twodox


People also ask

What is your understanding about JavaScript?

JavaScript is a text-based programming language used both on the client-side and server-side that allows you to make web pages interactive. Where HTML and CSS are languages that give structure and style to web pages, JavaScript gives web pages interactive elements that engage a user.

What is JavaScript simple explanation?

JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else. (Okay, not everything, but it is amazing what you can achieve with a few lines of JavaScript code.)

What is JavaScript in your own words?

Javascript (JS) is a scripting languages, primarily used on the Web. It is used to enhance HTML pages and is commonly found embedded in HTML code. JavaScript is an interpreted language. Thus, it doesn't need to be compiled. JavaScript renders web pages in an interactive and dynamic fashion.


1 Answers

From the MDN

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

Lots of properties (toString, for example) are inherited but likely not something you would want to iterate over when checking keys defined on an object.

like image 183
jakemingolla Avatar answered Oct 15 '22 08:10

jakemingolla