class Car{ constructor(name){ this.brand = name; } key(){ return 'I have a key of '+this.brand; } } mycar = new Car("Ford"); console.log(mycar.keyCreating the full source code for a Dream11-like fantasy sports app is quite extensive, but I'll provide a basic example focusing on key components like user authentication, contest management, team selection, and scoring logic using Node.js for the backend, MongoDB for data storage, and React.js for the frontend. Below is a simplified version to help you get started. ### Backend (Node.js with Express.js) #### 1. **Project Setup** Create a new directory for your backend and initialize a Node.js project. ```bash mkdir dream11-backend cd dream11-backend npm init -y ``` Install required dependencies: ```bash npm install express mongoose bcryptjs jsonwebtoken cors ``` #### 2. **Folder Structure** ``` dream11-backend/ ├── index.js ├── models/ │ ├── User.js │ ├── Contest.js │ ├── Team.js │ ├── Player.js │ └── index.js ├── routes/ │ ├── auth.js │ ├── contest.js │ └── team.js ├── controllers/ │ ├── authController.js │ ├── contestController.js │ └── teamController.js └── config/ └── config.js ``` #### 3. **Database Configuration** Create a MongoDB database and configure the connection in `config/config.js`. ```javascript // config/config.js module.exports = { mongoURI: 'your_mongodb_connection_string_here', secretOrKey: 'your_secret_key_here' }; ``` #### 4. **Models** Define Mongoose models for User, Contest, Team, and Player in `models/` directory. - **`models/User.js`** (User model) ```javascript const mongoose = require('mongoose'); const Schema = mongoose.Schema; const UserSchema = new Schema({ username: { type: String, required: true }, email: { type: String, required: true }, password: { type: String, required: true }, walletBalance: { type: Number, default: 1000 } // Initial wallet balance for users }); module.exports = mongoose.model('User', UserSchema); ``` Similarly, create models for Contest, Team, and Player. #### 5. **Controllers** Implement controllers to handle business logic in `controllers/` directory. - **`controllers/authController.js`** (Authentication controller) ```javascript const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const User = require('../models/User'); const config = require('../config/config'); exports.registerUser = async (req, res) => { const { username, email, password } = req.body; try { let user = await User.findOne({ email }); if (user) { return res.status(400).json({ message: 'User already exists' }); } user = new User({ username, email, password }); const salt = await bcrypt.genSalt(10); user.password = await bcrypt.hash(password, salt); await user.save(); // Return JWT token const payload = { id: user.id, username: user.username }; const token = jwt.sign(payload, config.secretOrKey); res.status(201).json({ token }); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } }; ``` Implement controllers for Contest and Team similarly. #### 6. **Routes** Define routes to handle API endpoints in `routes/` directory. - **`routes/auth.js`** (Authentication routes) ```javascript const express = require('express'); const router = express.Router(); const authController = require('../controllers/authController'); router.post('/register', authController.registerUser); module.exports = router; ``` Implement routes for Contest and Team similarly. #### 7. **Express Server Setup** Set up Express server in `index.js` to use defined routes and connect to MongoDB. ```javascript const express = require('express'); const mongoose = require('mongoose'); const config = require('./config/config'); const authRoutes = require('./routes/auth'); const contestRoutes = require('./routes/contest'); const teamRoutes = require('./routes/team'); const app = express(); // Middleware app.use(express.json()); app.use(cors()); // Routes app.use('/api/auth', authRoutes); app.use('/api/contests', contestRoutes); app.use('/api/teams', teamRoutes); // Connect to MongoDB mongoose.connect(config.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected')) .catch(err => console.error(err)); // Start server const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); ``` ### Frontend (React.js) #### 1. **Project Setup** Create a new directory for your frontend and initialize a React.js project. ```bash npx create-react-app dream11-frontend cd dream11-frontend npm install axios react-router-dom ``` #### 2. **Folder Structure** ``` dream11-frontend/ ├── src/ │ ├── components/ │ ├── pages/ │ ├── services/ │ ├── utils/ │ ├── App.js │ ├── index.js │ └── api.js ├── public/ └── package.json ``` #### 3. **API Service** Create a service file to handle API requests in `src/services/api.js`. ```javascript import axios from 'axios'; const api = axios.create({ baseURL: 'http://localhost:5000/api' }); export default api; ``` #### 4. **Components and Pages** Create React components and pages to interact with backend APIs in `src/components/` and `src/pages/` directories. Implement features like user registration, login, contest listing, team creation, etc., using React components and Axios for API requests. #### 5. **Integration** Integrate API service and components to build the frontend functionality. Example: User Registration Form (`src/pages/Register.js`) ```javascript import React, { useState } from 'react'; import api from '../services/api'; const Register = () => { const [formData, setFormData] = useState({ username: '', email: '', password: '' }); const handleInputChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; const handleSubmit = async (e) => { e.preventDefault(); try { const response = await api.post('/auth/register', formData); console.log('User registered:', response.data); // Redirect or show success message } catch (error) { console.error('Registration failed:', error.response.data); } }; return ( <div> <h2>Register</h2> <form onSubmit={handleSubmit}> <input type="text" name="username" placeholder="Username" onChange={handleInputChange} /> <input type="email" name="email" placeholder="Email" onChange={handleInputChange} /> <input type="password" name="password" placeholder="Password" onChange={handleInputChange} /> <button type="submit">Register</button> </form>
Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.
Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', function(line){
console.log("Hello, " + line);
});
Keyword | Description | Scope |
---|---|---|
var | Var is used to declare variables(old way of declaring variables) | Function or global scope |
let | let is also used to declare variables(new way) | Global or block Scope |
const | const is used to declare const values. Once the value is assigned, it can not be modified | Global or block Scope |
let greetings = `Hello ${name}`
const msg = `
hello
world!
`
An array is a collection of items or values.
let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);
let mobiles = ["iPhone", "Samsung", "Pixel"];
// accessing an array
console.log(mobiles[0]);
// changing an array element
mobiles[3] = "Nokia";
Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.
() => expression
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
.map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);
let [firstName, lastName] = ['Foo', 'Bar']
let {firstName, lastName} = {
firstName: 'Foo',
lastName: 'Bar'
}
const {
title,
firstName,
lastName,
...rest
} = record;
//Object spread
const post = {
...options,
type: "new"
}
//array spread
const users = [
...adminUsers,
...normalUsers
]
function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
console.log(`Hello ${name}!`);
}
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar
IF is used to execute a block of code based on a condition.
if(condition){
// code
}
Else part is used to execute the block of code when the condition fails.
if(condition){
// code
} else {
// code
}
Switch is used to replace nested If-Else statements.
switch(condition){
case 'value1' :
//code
[break;]
case 'value2' :
//code
[break;]
.......
default :
//code
[break;]
}
For loop is used to iterate a set of statements based on a condition.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while (condition) {
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (condition);
ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.
class className {
constructor() { ... } //Mandatory Class method
method1() { ... }
method2() { ... }
...
}
class Mobile {
constructor(model) {
this.name = model;
}
}
mbl = new Mobile("iPhone");