Uncaught ReferenceError: books is not defined

Write a function checkBasket() that lets you know if the item is in the basket or not.

Write a function checkBasket() that lets you know if the item is in the basket or not.

Here is the object basket:

amazonBasket = {
 glasses: 1,
 books: 2,
 floss: 100
}

What I tried in my JS:

function checkBasket(basket, lookingFor) {
   for(item of amazonBasket)
   {
       if(lookingFor===item){
           console.log("This item is in the basket")
       }else{
           console.log("This item is not in the basket")
       }
})
}

checkBasket(amazonbasket, books)

i.e:

checkBasket(amazonbasket,books)

it will return "This item is in the basket"

I don't understand why books are undefined.

How to send an object array from c# to javascript?

Im trying to send an array that contains some objects via connection made in SignalR, the connection is not a problem, everything works fine. When the data arrives to the view it is no longer the array i need to use. This is the class:

Im trying to send an array that contains some objects via connection made in SignalR, the connection is not a problem, everything works fine. When the data arrives to the view it is no longer the array i need to use. This is the class:

public class Empresa
    {
        public string nombre { get; set; }
        public int vidID { get; set; }
        public string img64 { get; set; }
        public string color { get; set; }
}

At the end the object will be something like this:

The object is send to the view and this is the output:

I have already tried with JsonConvert.SerializeObjectas i found on other threads, yet it doesnt seems to work. I tried to convert the data send with this jQuery.parseJSON(data) (Left) and with this JSON.parse(data)(Right); it throws an error on both cases as seen in the picture below.

I'm not sure if it is that way because the object sended is made this way:

private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();

var data = new List<Empresa>
{
new Empresa{nombre ="Globex Corp",color="red",vidId=1, img="data:image/jpeg;base64,blabla" },
new Empresa{nombre ="AM",color="blue",vidId=2, img="data:image/jpeg;base64,blabla" }
}
for(int i = 0; i<=6; i++)
{
_ar1.TryAdd(data[i].vidID, data[i]);
}

This is inside other function but it is the next one that involves the data send.

public IEnumerable<Empresa> GetArreglo()
{
return _ar1;
}

So far im not sure what could be wrong or if i need to aproach a different solution. If any more info is needed ill post it. And even it is obvious im a newby still learning on this.

How to create objects in JavaScript

How to create objects in JavaScript

In this article, we will see the different ways to instantiate objects in JavaScript.

Originally published at https://www.geeksforgeeks.org

JavaScript is a flexible object-oriented language when it comes to syntax. In this article, we will see the different ways to instantiate objects in JavaScript.

Before we proceed it is important to note that JavaScript is a class-less language and the functions are used in a way so that they simulate a class.

Using functions as class:

One of the easiest way to instantiate an object in JavaScript. We define a classical JavaScript function and create an object of the function using new keyword. The properties and methods of function are created using the this keyword. 

<script> 
	// Function acting as a Class. 
	function copyClass(name, age) { 
		this.name = name; 
		this.age = age; 
		this.printInfo = function() { 
			console.log(this.name); 
			console.log(this.age); 
		} 
	} 

// Creating the object of copyClass 
// and initializing the parameters. 
var obj = new copyClass("Vineet", 20); 

// Calling the method of copyClass. 
obj.printInfo(); 
</script> 

Output:

Vineet
20

Explanation: A class in OOPs have two major components, certain parameters and few member functions. In this method we declare a function similar to a class, there are two parameters, name and age ( the this keyword is used to differentiate the name and age of the class to the name and age of the arguments that are being supplied.) and a method printInfo that prints the value of these parameters. We then simple create an object obj of the copyClass, initialize it and call it’s method.

Using object literals:

Literals are smaller and simpler ways to define objects. Below we instantiate an object exactly same as the previous one just with the object literal.

<script> 
// Creating Object. 
var obj = { 
name : "", 
age : "", 
printInfo : function() { 
console.log(this.name); 
console.log(this.age); 

// Initializing the parameters. 
obj.name = "Vineet"; 
obj.age = 19; 

// Using method of the object. 
obj.printInfo(); 
</script> 

Output:

Vineet
20

Explanation: This method works same along the line of the previous one but instead of bundling the parameters ( name and age ) and the method ( printInfo ) inside of a function, we bundle them in the object itself, initialize the object and simply use the methods.

Singleton using a function:

The third way presented is a combination of the other two that we already saw. We can use a function to define a singleton object.

<script> 
// Creating singleton object. 
var obj = new function() { 
this.name = ""; 
this.age = ""; 
this.printInfo = function() { 
console.log(this.name); 
console.log(this.age); 
}; 

// Initializing object. 
obj.name = "Vineet"; 
obj.age = 20; 

// Calling method of the object. 
obj.printInfo(); 
</script> 

Output:

Vineet
20

Explanation: This is a combination of the previous two methods, we bundle the methods and parameters inside a function but don’t declare a separate function for it (Like copyClass in method 1). Instead we simple use the function structure to declare a object.

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading 

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

How to Sort an Array of Objects in JavaScript

3 Ways to Clone Objects in JavaScript

Javascript Objects Tutorial Example




Getting Started with JavaScript Object

Getting Started with JavaScript Object

Objects in JavaScript, just as in many other programming languages, can be compared to objects in real life. The concept of objects in JavaScript can be understood with real life, tangible objects.

Originally published by Zell Liew at https://scotch.io

An object is a type of data in JavaScript. It's the only value you can pass around as variables besides primitives. For this reason, objects are really important in JavaScript.

In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.

Table of Contents

  • What are objects
  • Object values
  • Getting the value of a property
  • Setting the value of a property
  • Deleting properties
  • Functions are Objects in JavaScript
  • Exercises to help you get better with objects 
What are objects

An object in JavaScript is a type of data that contains key-value pairs.

You can create objects by writing these key-value pairs within curly braces. If you intend to create multiple key-value pairs, you need to separate each pair with commas, like this:

const anObject = {
 key1: 'value1',
 key2: 'value2',
 key3: 'value3'
 // ...
}

Each key gives you a reference to a value. If you imagine an English dictionary, the keys are the words while the values are the definition of each word.

const dictionary = {
 dream: "a series of thoughts, images, and sensations occurring in a person's mind during sleep",
 happy: "feeling or showing pleasure or contentment",
 // ...
}

Since object stores key-value pairs, another analogy you can use is to compare objects in JavaScript with objects in real life.

For example, you can observe the device you're using to read this lesson. What device is this? What's its size? What's its operating system?

If you put these information together into a JavaScript object, it'd look like this:

const macbook = {
 operatingSystem: 'macOS Sierra',
 screenResolution: '2880x1800',
 screenSize: '15.4 inch',
 usbPorts: 2,
 hdmiPort: 1,
 storage: '512gb'
 // ... Other specs
}
Object values

Objects can contain any value that's valid in JavaScript. This means you can store primitives (like Strings and Numbers) and other objects.

const anObject = {
 string: 'Yay',
 number: 1,
 boolean: true,
 nullPrimitive: null,
 undefinedPrimitive: undefined,
 anotherObject: {},
 afunction: function () {} // more on functions later
 anArray: [] // more on array in the next lesson
}
Getting the value of a property

Keys are also called properties. You can use two methods to get the value of a property

The first method is through the dot notation, where you write the name of the object, followed by., followed by the property name:

const prop = object.property

So, if you'd like to get the storage of the macbook we declared above, you can write macbook.storage

const macbookStorage = macbook.storage
console.log(macbookStorage) // 512gb

The second method is through the bracket notation. Here, you write the name of the object, followed by a string of the property in square brackets ([]).

const macbookStorage = macbook['storage']
console.log(macbookStorage) // 512gb

Both methods work.

Normally, you'll use the dot notation. You'll only use the bracket notation in special occasions where the dot notation doesn't work. These special occasions include:

  1. When your property name is an invalid identifier
  2. When you need get the value of a property through a variable

Invalid identifiers

When you declare variables in JavaScript, you need to adhere to four rules:

  1. The variable must be written as a single word
  2. The variable must consist only of letters, numbers or underscores (0-9, a-z, A-Z, _).
  3. The variable cannot begin with a number.
  4. The variable cannot be any of these reserved keywords

If your variable follows these four rules, it's a valid identifier; if your variable doesn't follow any of these rules, it's an invalide identifier.

Objects can have invalid identifiers as properties. Here's one example:

const ObjWithInvalidIdentifer = {
 'First Name': 'Zell'
}

When you have an invalid identifier, you can't use the dot notation. You need to use the bracket notation:

const firstName = ObjWithInvalidIdentifer.First Name // Syntax Error: Unexpected identifier
const firstName2 = ObjWithInvalidIdentifer['First Name'] // Zell

Of course, when you create objects, try to make properties with valid identifiers so you can use the dot notation. Don't make life hard for yourself!

Getting the value of a property through a variable.

When you write more advanced code, you may need to get the value of a property through a variable. In this case, you can only use the bracket notation.

For example, let's say you store the property to search in a variable called propertyToGet.

const propertyToGet = 'storage'

There's no property called propertyToGet in the object, so you can't use the dot notation. If you try doing it, you'll get undefined.

const storageWithDotNotation = macbook.propertyToGet
console.log(storageWithDotNotation) // undefined

You can only use the bracket notation, like this:

const macbookStorage = macbook[propertyToGet]
console.log(macbookStorage) // 512gb

That's all you need to know about getting property values. Let's move on and learn to set property values.

Setting the value of a property

You can set the value of a property either with the dot notation or the bracket notation. Likewise, the dot notation is always preferred.

// Dot notation
macbook.storage = '256gb'

// Bracket notation
macbook['usbPorts'] = 2

console.log(macbook)
// {
//  storage: '256gb',
//  usbPorts: 2
// }

Deleting properties

You can delete key-value pairs from objects with the delete keyword. To do so, you write delete, followed by the property either in dot or bracket notation.

delete object.property

Here's an example where we delete the storage property from the macbook Object.

delete macbook.storage
console.log(macbook)
// The storage property is already deleted, hence you don't see it anymore when you console.log it
// {
//  usbPorts: 2
// }
Functions are Objects in JavaScript

Functions are a special kind of Object in JavaScript. It can have properties too (even though you'd most likely won't declare any).

// You can add properties to functions
function sayName () {}
sayName.property = 'Hallelujah'

console.log(sayName.property)
// Hallelujah

Since functions are objects, you can write functions as values in objects. The properties that contain functions as their values are called methods.

const anObject = {
 aMethod: function() {
   // Do something in function
 }
}

In the following example, we say playMusic is a method of macbook.

const macbook = {
 playMusic: function () {
   /* some code to play music */
 }
}

Since methods are functions, they behave exactly like functions.

To call a method, you write parenthesis () after getting the method through the dot or bracket notation

// Calling a method with the dot notation
macbook.playMusic()

// Calling a method with the bracket notation
macbook'playMusic'

You can also add arguments to methods, just like normal functions:

const greeter = {
 sayHello: function (name) {
   console.log('Hello ' + name + '!')
 }
}

greeter.sayHello('Zell')
// Hello Zell!

You may hear phrases like "higher order functions" and "functions are first class objects" when you browse outside tutorials. Ignore these phrases. They both mean functions are objects, which means you can pass functions around as a variable. People like to introduce important-sounding jargons to make functions sound more amazing (and confusing) than they really are.

Exercises to help you get better with objects

You'll use a lot of objects in JavaScript. Make sure you know them inside-out. Here are some exercises to use can for practice:

  1. Make an empty object
  2. Make a property for your object with the dot notation. Give it a value
  3. Make a property for your object with the bracket notation. Give it a value
  4. Get the value of a property with the dot notation
  5. Get the value of a property with the square bracket notation
  6. Set the value of a property with the dot notation
  7. Set the value of a property with the square bracket notation
  8. Make a method. Call this method
  9. Make a method that takes in an argument. Call this method

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about JavaScript

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

New ES2019 Features Every JavaScript Developer Should Know

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

JavaScript Basics Before You Learn React

Build a CMS with Laravel and Vue

Google’s Go Essentials For Node.js / JavaScript Developers